I set date format as dd/MM/yyyy for datepicker. When I select the date, it shows the date as expected. Now I added a custom validation to validate manual input.
What I tried:
I don't add a custom validation to formcontrol.
this.control = new FormControl(null);And I create a method to show error message against the datepicker input (#pickerInput).
<input matInput [matDatepicker]="picker" [formControl]="control" #pickerInput/> <mat-hint>DD/MM/YYYY</mat-hint> <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> <mat-error *ngIf="control?.invalid">{{getErrorMessage(pickerInput.value)}}</mat-error>And getErrorMessage is
getErrorMessage(input: string) { if (input) { const regexPattern = /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/; const isValid = regexPattern.test(input); if (!isValid) { this.control?.setErrors({ invalidDateFormat: true }); this.control?.updateValueAndValidity(); return 'Invalid Date Format'; } else { this.control?.setErrors({ invalidDateFormat: null }); this.control?.updateValueAndValidity(); return null; } } return null; }Steps:
- When I selected a date from calendar, it shows the date as expected.
- I delete the last number. The error shows as expected.
- I added the number back. The error message has gone but the field is marked as red.
I think the datepicker value is validated as MM/dd/yyyy? The control has an error.
{ "matDatepickerParse": { "text": "24/04/2023" } } 1 Related questions 2 mat-datepicker with filtered input 0 Binding formControl to external formGroup in Angular makes mat-error not to work 83 How to change Mat-Datepicker date format to DD/MM/YYYY in simplest way? Related questions 2 mat-datepicker with filtered input 0 Binding formControl to external formGroup in Angular makes mat-error not to work 83 How to change Mat-Datepicker date format to DD/MM/YYYY in simplest way? 1 How to format user typed input in mat-datepicker input? 0 no full control for datepicker validation using input matDatepickerFilter Load 2 more related questions Show fewer related questions Reset to default