I have 2 datetime picker, endDate cannot be less than startDate
endDateAfterOrEqualValidator(formGroup): any {
var startDateTimestamp: number;
var en
a mat-error
only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use a ErrorStateMatcher
In your case it would look like this:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const invalidCtrl = !!(control && control.invalid);
const invalidParent = !!(control && control.parent && control.parent.invalid);
return (invalidCtrl || invalidParent);
}
}
Also worth mentioning, it's not recommended to have two bindings, i.e formControl
and ngModel
. Remove the ngModel
and utilize the form control instead. If you receive your start date and end date at a later point, you can use patchValue
(just set some values to form) or setValue
(set all values to form)
mark in component the errorstatematcher:
matcher = new MyErrorStateMatcher();
As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:
checkDates(group: FormGroup) {
if (group.controls.endDate.value < group.controls.startDate.value) {
return { endDateLessThanStartDate: true }
}
return null;
}
and then mark the error state matcher in your template:
End date cannot be earlier than start date
Here's a StackBlitz