角2组验证

角2组验证

问题描述:

鉴于简单的登记表:角2组验证

this.registerForm = this.formBuilder.group({ 
    email:['', Validators.compose([ 
    Validators.required, 
    Validators.pattern('[email protected]+\..+'), 
    ]), this.validators.isTaken], 
    matchingPassword: this.formBuilder.group({ 
    password: ['', Validators.compose([ 
      Validators.required, 
      Validators.maxLength(30), 
      Validators.minLength(8) 
     ])], 
    passwordConfirmation: ['', Validators.compose([ 
      Validators.required, 
     ])] 
    }, {validator: this.validators.match}) 
}) 

我试图验证密码确认匹配,所以我施加匹配验证器,以形成组。但是现在我面临的情况是,当字段本身显示为有效(带有绿色边框,因为它的所有验证器都通过了),但组验证器不是,我需要它们显示为红色。

enter image description here

所以我应该改变NG-有效手动NG-无效或有一些技巧在更好的方式来解决这一问题?

+0

为了您的具体的例子,我把自定义matchingPasswordValidator在'passwordConfirmation'领域,因为该领域的内容时,它匹配的密码才有效。对于更通用的组验证程序,我只会针对整个组发出一般错误消息。 –

+0

@HarryNinh,这种方法的问题是,如果我将匹配验证器添加到'passwordConfirmation',它只会触发此字段的更改。我的意思是,如果您更改'password'字段以使其匹配'passwordConfirmation',则最后一个仍会标记为无效,因为未在该字段上运行验证。 – SET

+0

啊,你可以订阅'password'的'valueChanges'事件来调用'passwordConfirmationControl.updateValueandValidity()'函数。 –

我刚刚在这里回答了这个问题[1]。

基本上,角度并不假定你想使组中的所有字段无效,因为该组无效。您可以在模板本身补充这些信息。

我没有你的模板,但我可以或多或少假设你可以改变你的控件以下列方式将被无效的:

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Password" formControlName="password"> 

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Confirm password" formControlName="passwordConfirmation"> 

你可能需要调整占位符和错误名称返回由自定义验证器匹配

[1] FormControl`s of nested FormGroup are ng-valid although FromGroup is ng-invalid