Angular material date-picker min and max date validation messages
Asked Answered
F

1

20

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?

Feathering answered 22/2, 2019 at 13:44 Comment(1)
Do you want to show error message for minDate without set minDate value?Fusibility
C
42

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 }}
Condone answered 22/2, 2019 at 14:7 Comment(3)
Thank you. It helped. Mine one is Reactive form! So I used {{ formgroup.get(field.key).errors | json }} instead! And I can handle now! Thanks!Feathering
Note: This matDatepickerMax error is automatically added to your form when you set [maxDate]. See also github.com/angular/components/blob/master/src/dev-app/…Slog
Is it possible to set the max range and max date?Surrogate

© 2022 - 2024 — McMap. All rights reserved.