from date and to date validation in angular 9
export class CustomeDateValidators {
static fromToDate(fromDateField: string, toDateField: string, errorName: string = 'fromToDate'): ValidatorFn {
return (formGroup: AbstractControl): { [key: string]: boolean } | null => {
const fromDate = formGroup.get(fromDateField).value;
const toDate = formGroup.get(toDateField).value;
// Ausing the fromDate and toDate are numbers. In not convert them first after null check
if ((fromDate !== null && toDate !== null) && fromDate > toDate) {
return {[errorName]: true};
}
return null;
};
}
}
/*--- implementations ---*/
this.form = this.fb.group({
fromDate: null,
toDate: null,
}, { validator: [
//Default error with this validator: {fromToDate: true}
CustomeDateValidators.fromToDate('fromDate', 'toDate')
// For custome error name like: {customeErrorName: true}, pass third optional parameter with custome name
// CustomeDateValidators.fromToDate('fromDate', 'toDate', 'customeErrorName')
]});