- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有类似的问题:
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 issueswith Closure Compiler renaming. Use the
FormBuilder#group
overloadwithAbstractControlOptions
instead. Note thatAbstractControlOptions
expectsvalidators
andasyncValidators
tobe valid validators. If you have custom validators, make sure theirvalidation function parameter isAbstractControl
and not asub-class, such asFormGroup
. These functions will be called with anobject of typeAbstractControl
and that cannot be automaticallydowncast to a subclass, so TypeScript sees this as an error. Forexample, change the(group: FormGroup) => ValidationErrors|null
signature to be(group: AbstractControl) => ValidationErrors|null
.(deprecation)
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/
我是一名优秀的程序员,十分优秀!