gpt4 book ai didi

angular - FormBuilder 组已被验证器弃用

转载 作者:行者123 更新时间:2023-12-04 15:57:42 26 4
gpt4 key购买 nike

我有类似的问题:
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 overloadwith AbstractControlOptions instead. Note thatAbstractControlOptions expects validators and asyncValidators tobe valid validators. If you have custom validators, make sure theirvalidation function parameter is AbstractControl and not asub-class, such as FormGroup. These functions will be called with anobject of type AbstractControl and that cannot be automaticallydowncast to a subclass, so TypeScript sees this as an error. Forexample, change the (group: FormGroup) => ValidationErrors|nullsignature 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com