Angular Material Date Picker Invalid Date Validation
In Angular Material most of the time we will use Angular Material Date picker in order to implement the date related field. But most of the time user will enter some wrong date or give some wrong input like string number etc. So If you face this scenario then you should read this article and I will explain how easily you can validate wrong input in Angular Material Date picker.
Introduction
In Angular Material Date Picker this validation is by default available but most of the people do not aware of it. Most of the time people will write custom directive or custom validator to validate wrong input in the date picker. Which is not necessary at all we need to write clean code and framework related code. If Angular Material provides one feature as a default feature then we should use that feature. So lets discuss about the implementation.
Implement Invalid Date Validation In Reactive Form
In Order to implement the invalid date validation and If you are using Reactive Form then you do not need to write any extra Validator in the Form Builder. Because that validation is inbuilt, so when you write any wrong input in the Angular Material Date Picker then it will show you the field in red color, it means that, it is already doing the validation for invalid field. So now we just need show the to the user invalid date message and we need to write this below code in your html.
<mat-error *ngIf="formGroup.controls['dateFormControl'].hasError('matDatepickerParse')">
Invalid date
</mat-error>
So that is all you need to write this above piece of code and you can easily validate invalid input in Angular Material Date picker. But if you are doing a required validation then this logic will change why it is because this invalid date validation will also work required validation by default. It means that when you give any invalid input like number or string then it will capture in the new Date(inputValue) object by default, So if the input value is not a proper date string then it will throw an error and also value will be undefined, so the required validation will also work at the same time. So for required validation you can use this below code.
<mat-error *ngIf="formGroup.controls['dateFormControl'].hasError('required')">
Invalid date and this field is required
</mat-error>
Conclusion
So I hope you will get an understanding that how you can leverage the Angular Material Date picker default validation to validate invalid date and how to use required validation for the date picker required and as well as invalid date validation.