验证器已弃用 FormBuilder 组

问题描述

我有类似的问题:

How do I resolve the error I am encountering using custom Validator syntax?

FormBuilder group is deprecated

我已经阅读了那个问题,但问题仍然出现在 linter 中:

group 已弃用:此 API 不是类型安全的,可能会导致问题 使用 Closure Compiler 重命名。使用 FormBuilder#group 重载 用 AbstractControlOptions 代替。注意 AbstractControlOptions 期望 validatorsasyncValidators 成为有效的验证者。如果您有自定义验证器,请确保它们 验证函数参数是 AbstractControl 而不是 子类,例如 FormGroup。这些函数将被调用 AbstractControl 类型的对象并且不能自动 向下转换为子类,因此 TypeScript 将其视为错误。为了 例如,更改 (group: FormGroup) => ValidationErrors|null 签名为 (group: AbstractControl) => ValidationErrors|null。 (弃用)

这是我的 formBuilder:

registerForm = this._fb.group({
        firstname: ["",[Validators.required]],lastname: ["",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 部分正确。在 formBuilder 中它必须是 validators 而不是 validator,即使它只是一个验证器,再次对不起 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;
            }
        };
    }
}
,

错误在哪里?。我做了一个 stackblitz with your code 但我看不到它

顺便说一句,我不太喜欢使用 setError 将错误“放入”控件中。

如果你不使用 mat-error,你可以简单地询问 form.errors。

如果你使用 mat-error 你可以