在我的反应形式中,我有两个密码字段。两个匹配两个字段的值我创建了一个自定义验证器,然后在 ts 文件的表单组中分配该验证器。代码如下:
this.registerForm = new FormGroup({
title: new FormControl("", Validators.required),
firstName: new FormControl("", Validators.required),
lastName: new FormControl("", Validators.required),
password: new FormControl("", [Validators.required, Validators.minLength(6)]),
confirmPassword: new FormControl("", Validators.required),
acceptTerms: new FormControl("", Validators.required)
},
{
validator: MustMatch('password', 'confirmPassword')
});
必须匹配验证器代码:
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch11111) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch11111: true });
} else {
matchingControl.setErrors(null);
}
}
}
但 MustMatch 显示错误如下:
'{验证器类型的参数:(formGroup:FormGroup)=> void; }' 不可分配给类型为 'ValidatorFn | 的参数 验证器Fn[] | 抽象控制选项'。对象字面量只能指定已知属性,而 'validator' 类型中不存在 'ValidatorFn | 验证器Fn[] | 抽象控制选项'。
66 validator: MustMatch('password', 'confirmPassword')
由于我是角度新手,任何人都可以帮我解决这个问题。