我有类似的问题:
How do I resolve the error I am encountering using custom Validator syntax?
FormBuilder group is deprecated
我已经阅读了问题,但问题仍然出现在 linter 中:
group is deprecated: This API is not typesafe and can result in issues with Closure Compiler renaming. Use the
FormBuilder#group
overload withAbstractControlOptions
instead. Note thatAbstractControlOptions
expectsvalidators
andasyncValidators
to be valid validators. If you have custom validators, make sure their validation function parameter isAbstractControl
and not a sub-class, such asFormGroup
. These functions will be called with an object of typeAbstractControl
and that cannot be automatically downcast to a subclass, so TypeScript sees this as an error. For example, change the(group: FormGroup) => ValidationErrors|null
signature to be(group: AbstractControl) => ValidationErrors|null
. (deprecation)
这是我的 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;
}
};
}
}
知道为什么吗?我正在返回正确的对象。 :/
最佳答案
@OwenKelvin 部分正确。必须是validators
相反 validator
在 formBuilder 中,即使它只是一个验证器,再次对不起 Owen。
但第二个问题是在验证器中。该函数应接收 AbstractControl
相反 FormGroup
.所以下面的代码是正确的:
export class PasswordValidator {
static confirmed = (controlName: string, matchingControlName: string) => {
return (control: AbstractControl): ValidationErrors | null => {
const input = control.get(controlName);
const matchingInput = control.get(matchingControlName);
if (input === null || matchingInput === null) {
return null;
}
if (matchingInput?.errors && !matchingInput.errors.confirmedValidator) {
return null;
}
if (input.value !== matchingInput.value) {
matchingInput.setErrors({ confirmedValidator: true });
return ({ confirmedValidator: true });
} else {
matchingInput.setErrors(null);
return null;
}
};
}
}
关于angular - FormBuilder 组已被验证器弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65814492/