Angular 角度2组验证
提供简单的登记表:Angular 角度2组验证,angular,angular2-forms,Angular,Angular2 Forms,提供简单的登记表: this.registerForm = this.formBuilder.group({ email:['', Validators.compose([ Validators.required, Validators.pattern('.+@.+\..+'), ]), this.validators.isTaken], matchingPassword: this.formBuilder.group({ password: ['
this.registerForm = this.formBuilder.group({
email:['', Validators.compose([
Validators.required,
Validators.pattern('.+@.+\..+'),
]), 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})
})
我正在尝试验证密码确认匹配,所以我正在将匹配验证器应用于表单组。但现在我面临的情况是,字段本身显示为有效(带绿色边框,因为它的所有验证器都通过了),但组验证器没有,我需要它们显示为红色
所以,我应该手动将ng valid更改为ng invalid,还是有一些技巧可以更好地解决这个问题?我刚才在这里回答了这个问题[1] 基本上,angular不会因为组无效而假定要使组的所有字段无效。您可以在模板本身中补充这些信息 我没有您的模板,但我可以或多或少地假设您可以通过以下方式将控件更改为无效:
<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] 对于您的特定示例,我会将自定义匹配PasswordValidator放在
passwordConfirmation
字段中,因为该字段的内容只有在与密码匹配时才有效。对于更通用的组验证器,我只会收到整个组的一般错误消息。@HarryNinh,这种方法的问题是,如果我将匹配验证器设置为passwordConfirmation
,它只会在该字段更改时触发。我的意思是,如果您更改password
字段,使其与passwordConfirmation
匹配,则最后一个字段仍将标记为无效,因为验证未在该字段上运行。啊,您可以订阅password
的valueChanges
事件来调用passwordConfirmationControl.updateValue和validity()
function.SET,您找到解决方案了吗?