【发布时间】:2021-04-25 02:38:37
【问题描述】:
我有类似的问题:
How do I resolve the error I am encountering using custom Validator syntax?
FormBuilder group is deprecated
我已阅读问题,但问题仍然出现在 linter 中:
group 已弃用:此 API 不是类型安全的,可能会导致问题 使用闭包编译器重命名。使用
FormBuilder#group重载 用AbstractControlOptions代替。注意AbstractControlOptions期望validators和asyncValidators到 成为验证者。如果您有自定义验证器,请确保它们的 验证函数参数是AbstractControl而不是 子类,例如FormGroup。这些函数将被调用AbstractControl类型的对象,不能自动 向下转换为子类,因此 TypeScript 将此视为错误。为了 例如,更改(group: FormGroup) => ValidationErrors|null签名为(group: AbstractControl) => ValidationErrors|null。 (弃用)
这是我的 formBuilder:
registerForm = this._fb.group({
firstname: ["", [Validators.required]],
lastname: ["", [Validators.required]],
email: ["", [Validators.required, Validators.email]],
password: ["", [PasswordValidator.strength]],
confirmPassword: ["", [Validators.required]]
}, {
validator: PasswordValidator.confirmed("password", "confirmPassword")
});
还有我的验证器:
export class PasswordValidator {
static confirmed = (controlName: string, matchingControlName: string) => {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
return null;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true });
return ({ confirmedValidator: true });
} else {
matchingControl.setErrors(null);
return null;
}
};
}
}
知道为什么吗?我正在返回正确的对象。 :/
【问题讨论】:
-
是
validators而不是validator -
修正错字(删除括号)。但这不是原因
-
我的意思是由于
validator: PasswordValidator.confirmed("password", "confirmPassword")这一行而引发了错误 -
嗯,是的,我知道,但是,我该如何解决呢?
-
只需添加一个...
validators: [PasswordValidator.confirmed("password", "confirmPassword")]
标签: angular typescript angular-reactive-forms