I'm trying to use custom validator to compare if the end time is greater than the start time.
code:
function timeValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined && (isNaN(control.value) || control.get('fromTime').value > control.get('toTime').value)) {
return { 'ageRange': true };
}
return null;
};
}
From formgroup
toTime: new FormControl(null, [Validators.required, timeValidator(this.fromTime,this.toTime)]),
I'm getting a error once I run this like: Cannot read property 'value' of null
on the line if (control.value !== undefined && (isNaN(control.value) || control.get('fromTime').value > control.get('toTime').value))
I need some help in fixing this. Thank you
Your custom validator should be put at FormGroup level not FormControl level. Also you should pass the function in as an argument, meaning without the () brackets because timeValidator is a callback function. () tells the js engine to execute the function. But what you want is pass in the function as an argument, so it could be executed later.
either
constructor(private fb: FormBuilder){}
...
this.form = this.fb.group({
fromTime: [''],
toTime: ['']
}, { validator: timeValidator})
OR
form = new FormGroup({
toTime: new FormControl(null),
fromTime: new FormControl(null),
}, { validator: timeValidator})
Your custom validator also shouldn't be returning a function. It should be returning a name:boolean key-value pair. E.g. isEndGTStart: true or null if false
E.g.
export function timeValidator(fg: FormGroup){
const fromTime = fg.get("fromTime").value;
const toTime = fg.get("toTime).value;
return toTime > fromTime ? { isEndGTStart: true } : null
}