[英]Problems with the custom validator in Angular
我知道这个问题已经在许多其他帖子中提出过,但在所有建议的解决方案中我找不到能为我解决问题的解决方案。
我正在尝试创建一个验证器来检查输入的确认密码是否与密码相同。
这是我的构建表单代码:
this.form = new FormGroup({
name: new FormControl('', [Validators.required]),
surname : new FormControl('', [Validators.required]),
username: new FormControl('', [Validators.required, Validators.email]),
tempUsername: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]),
passwordTemp: new FormControl('', [Validators.required]),
}, { validator: this.matchingPasswords }
);
}
这是我的验证器方法:
public matchingPasswords(c: AbstractControl): ValidationErrors | null {
const password = c.get(['passwords']);
const confirmPassword = c.get(['passwordTemp']);
if (password.value !== confirmPassword.value) {
return { mismatchedPasswords: true };
}
return null;
}
在构建表单的第 8 行中,出现以下错误:
TS2345:'{ 验证器类型的参数:(c: AbstractControl) => ValidationErrors; }' 不可分配给 'ValidatorFn | 类型的参数验证器[] | 抽象控制选项'。 对象字面量只能指定已知属性,并且类型“ValidatorFn | 中不存在”“validator” 验证器[] | 抽象控制选项'。
有任何想法吗?
您应该使用validators
而不是validator
:
this.form = new FormGroup({
// fields
}, { validators: this.matchingPasswords });
也许将matchingPasswords
的密码移动到导出的实用程序 function 也更好,但这只是个人代码偏好。
其他工作符号是:
this.form = new FormGroup({
// fields
}, this.matchingPasswords);
this.form = new FormGroup({
// fields
}, [this.matchingPasswords]);
使用验证器而不是验证器
{ validators: this.matchingPasswords }
和这个
public matchingPasswords: ValidatorFn = (c: AbstractControl): ValidationErrors | null => {
const password = c.get('passwords');
const confirmPassword = c.get('passwordTemp');
if (password && confirmPassword && password.value !== confirmPassword.value) {
return { mismatchedPasswords: true };
}
return null;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.