I set date format as dd/MM/yyyy to display dd/MM/yyyy for datepicker but control validation does not validate as dd/MM/yyyy

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:

  1. When I selected a date from calendar, it shows the date as expected.

enter image description here

  1. I delete the last number. The error shows as expected.

enter image description here

  1. I added the number back. The error message has gone but the field is marked as red.

enter image description here

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

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like