I want to implement a custom Cross-field validator using the ValidatorFn interface from Angular.
This is my code: (I followed the provided steps on https://angular.io/guide/form-validation#cross-field-validation)
import { ValidatorFn, ValidationErrors, FormGroup } from "@angular/forms";
/**
* This validator implements the ValidatorFn Interface from Angular.
*
* @param formGroup- the FormGroup that needs Validation
*
* @returns null if the form is valid, else some {@link ValidatorErrors}
*/
export const CompleteBloodpressureValidator: ValidatorFn = (formGroup: FormGroup) => {
const bloodpressureSys = formGroup.get("bloodPressureSysFormControl");
const bloodpressureDia = formGroup.get("bloodPressureDiaFormControl");
if (bloodpressureSys != null && bloodpressureDia == null || bloodpressureSys == null && bloodpressureDia != null){
// return some custom ValidatorErrors
return {
bloodPressureIncomplete: true
};
}
// if everything is fine, return null
return null;
}
But the angular compiler keeps telling me the following:
Type '(fromGroup: FormGroup) => { bloodPressureIncomplete: boolean; } | null' is not assignable to type 'ValidatorFn'.
Types of parameters 'fromGroup' and 'control' are incompatible.
Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.ts(2322)
This doesn't make any sense in my opinion, my implementation of ValidatorFn is exactly how it should look like.
Any advice what I do wrong here?
So the answer to this question is to update the TypeScript version or exchange
formGroup: FormGroup
with
formGroup: AbstractControl
It seems to be caused by a bug in the TypeScript version.
EDIT: updating to the newest TypeScript version does not change anything. I guess this is maybe a fault in the Angular Documentatation.
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