我正在使用角度形式来创建一个寄存器形式。我已经做了一个自定义验证器,它检查密码是否与确认密码字段相同。虽然“密码不匹配”的错误没有显示,但在输入所有字段之前,输入仍然是红色的。
具有自定义验证器方法checkPasswords
的表单生成器
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required]],
confirmPassword: ['', [Validators.required]]
},
{ validator: this.checkPasswords });
checkPasswords(group: FormGroup) {
// here we have the 'passwords' group
let pass = group.get('password').value;
let confirmPassword = group.get('confirmPassword').value;
return pass === confirmPassword ? null : { notSame: true };
}
以及下面的html
<mat-form-field required>
<input matInput type="password" placeholder="Password" formControlName="password">
<mat-error>Password is not valid</mat-error>
</mat-form-field>
<mat-form-field required>
<input matInput type="password" placeholder="Confirm password"
formControlName="confirmPassword"
[errorStateMatcher]="matcher">
<mat-error *ngIf="registerForm.hasError('notSame')">Passwords do not match</mat-error>
</mat-form-field>
我尝试过进行一些调试,我认为这是因为表单组状态在输入所有字段之前都是“无效”的,但是confirmPassword
的窗体组控件显示为有效。如何获得confirmPassword的状态以使用其控件的状态?
谢谢
发布于 2019-10-18 03:51:52
这是因为有棱角的材料。如果给定控件上没有错误,则<mat-error>
将不可见。您需要在confirmPassword
字段上设置错误以显示错误。
发布于 2019-10-18 03:01:20
所有输入都是红色的吗?
可能是物质输入首先检查控件是否被触摸或脏(在将其标记为红色之前),但如果表单本身无效,则立即将其标记为红色。
查看代码,您的registerForm
末尾的验证器似乎是在用户填充confirmPassword
字段之前运行的,将registerForm
标记为无效。
备选方案:
checkPasswords
验证器应用于confirmPassword
而不是整个表单?checkPasswords
中的confirmPassword
控件是否也被触摸或脏(除了https://stackoverflow.com/questions/58438783
复制相似问题