验证器已弃用FormBuilder组

我有与这里类似的问题:

如何解决使用自定义验证器语法时遇到的错误?

不推荐使用 FormBuilder 组

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

不推荐使用组:此 API 不是类型安全的,可能会导致 Closure Compiler 重命名问题。使用FormBuilder#group重载 withAbstractControlOptions代替。请注意,
AbstractControlOptions期望validatorsasyncValidators将成为有效的验证器。如果您有自定义验证器,请确保它们的验证函数参数是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;
            }
        };
    }
}

知道为什么吗?我正在返回正确的对象。:/

回答

@OwenKelvin 部分正确。它必须是validators不是validator在formBuilder,尽管这只是一个验证,对不起欧文一次。

但第二个问题是在验证器中。该函数应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;
            }
        };
    }
}


以上是验证器已弃用FormBuilder组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>