Angular forms date validations code example
Example 1: 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;
if ((fromDate !== null && toDate !== null) && fromDate > toDate) {
return {[errorName]: true};
}
return null;
};
}
}
this.form = this.fb.group({
fromDate: null,
toDate: null,
}, { validator: [
CustomeDateValidators.fromToDate('fromDate', 'toDate')
]});
Example 2: angular input date pattern validation
(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))