date validator in angular code example
Example 1: angular input date pattern validation
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d
Example 2: angular from date to date validation
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 3: from date and to date validation in angular 8
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')
]});