angulartypescriptangular-materialangular-material-datetimepicker

Angular material date-picker min and max date validation messages


How to show the validation messages for min and max dates validation errors in Angular Material Datepicker

<input [min]="minDate" [max]="maxDate" matInput [matDatepicker]="picker" [formControlName]="date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>

<mat-error class="error-message" *ngIf="formgroup.get('date').hasError('required') && (formgroup.get('date').dirty || formgroup.get('date').touched)">Date is Required</mat-error>

Here Required validation has been set.

Like same I want to show Date should be higher than 01/01/2019 message if user typed the date which is less than minDate.

I knew that all the previous dates would be disabled if we set minDate. But in this application, we allow user to type the date too! So when user enters the date which is previous than the minDate defined, I want to show the error message!

Any way to achieve it?


Solution

  • You can use the reference to the ngModel to know if the date is in error.

    In this stackblitz, I have made it so that you can see the errors applied to the input (so that you can know the error), and also displayed the error when the input is in error.

    <mat-form-field class="example-full-width">
      <input matInput #input="ngModel" [(ngModel)]="date" [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    
      <mat-error *ngIf="input.hasError('matDatepickerMax')">Date should be inferior</mat-error>
    
    </mat-form-field>
    
    <br><br><br>
    {{ input.errors | json }}