我在使用 Angular(v4.3.6)在模型驱动表单上显示验证错误时遇到了一些麻烦。
在我的模型中,我有以下内容:
this.registerForm = formBuilder.group({
'email':[null,Validators.compose([Validators.required, ValidateEmail])],
'firstName':[null, Validators.required],
'lastName':[null, Validators.required],
'passwordGroup': formBuilder.group({
'password':[null, Validators.compose([Validators.required,Validators.minLength(8)])],
'passwordConfirmation':[null, Validators.required],
},{validator: ValidatePasswordConfirmation})
});
引用的 ValidatePasswordConfirmation 自定义验证器如下:
export function ValidatePasswordConfirmation(group: FormGroup) {
if(group.value.password !== group.value.passwordConfirmation){
return { 'no-match':true };
}
return null;
}
最后,在我的模板中,我有以下内容:
<md-form-field>
<input mdInput name="passwordConfirmation" placeholder="Confirm password" [formControl]="registerForm.controls['passwordGroup'].controls['passwordConfirmation']" [(ngModel)]="model.passwordConfirmation" type="password">
<md-error *ngIf="registerForm.controls['passwordGroup'].controls['passwordConfirmation'].hasError('required')">
Password confirmation is required
</md-error>
<md-error *ngIf="registerForm.controls['passwordGroup'].hasError('no-match')">
Passwords don't match
</md-error>
</md-form-field>
但是,由“不匹配”错误控制的 md 错误永远不会出现。因此,为了在页面上调试它,我添加了以下内容:
no-match = {{registerForm.controls['passwordGroup'].hasError('no-match')}}
invalid = {{registerForm.controls['passwordGroup'].invalid}}
不出所料,调试行显示真/假,如您所料。但是,永远不会显示“md-error”……除非显示“必需”错误。我有一种感觉,问题是由于 [formControl] 引用了 passwordConfirmation FormControl,因此如果它无效,则不会显示 md 错误。但是,我希望在外部 FormGroup 无效时显示此错误。
关于我在这里出错的任何指示都会非常有帮助!
最后,我尝试了其他一些方法,例如在 PasswordConfirmation FormControl 上设置错误,这很有效,但我想知道为什么我当前的实现失败了。