I have the simillar issue as here:
How do I resolve the error I am encountering using custom Validator syntax?
FormBuilder group is deprecated
I've read that Questions, but the issue still occurs in linter:
group is deprecated: This API is not typesafe and can result in issues with Closure Compiler renaming. Use the
FormBuilder#groupoverload withAbstractControlOptionsinstead. Note thatAbstractControlOptionsexpectsvalidatorsandasyncValidatorsto be valid validators. If you have custom validators, make sure their validation function parameter isAbstractControland not a sub-class, such asFormGroup. These functions will be called with an object of typeAbstractControland that cannot be automatically downcast to a subclass, so TypeScript sees this as an error. For example, change the(group: FormGroup) => ValidationErrors|nullsignature to be(group: AbstractControl) => ValidationErrors|null. (deprecation)
And here is my 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")
});
And my validator:
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;
}
};
}
}
Any idea why? I'm returning the proper object. :/
@OwenKelvin was partially right. It have to be validators instead validator in formBuilder, even though it's just one validator, sorry Owen again.
But the second problem was in validator. The function should receives AbstractControl instead FormGroup. So the following code is correct:
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;
}
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With