manti13
manti13

Reputation: 111

How can I validate the Date from a Angular material Datepicker based on another Datepicker

I have 2 Angular Material Datepickers and want to implement the following validation: -The date of the first datepicker has to be the min-date of the 2nd one

Here are my datepickers

<mat-form-field appearance="legacy" [style.width.%]="45">
  <mat-label>Phasenbeginn</mat-label>
  <input matInput  placeholder="Beginn" [matDatepicker]="picker" formControlName="pStart">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>                                   
          
<mat-form-field appearance="legacy" [style.width.%]="45">
  <mat-label>Phasenende</mat-label>
  <input matInput  placeholder="Ende" [matDatepicker]="picker2" formControlName="pEnd">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
 </mat-form-field>

On the material documentation they say, that you can add a "[min] = minDate" binding to the input, but I think this is only used for static dates, saved in a variable.

I want to do something like this, on the 2nd picker

<input matInput [min]="picker.value" placeholder="Ende" [matDatepicker]="picker2" formControlName="pEnd">

Upvotes: 1

Views: 5867

Answers (1)

blazebot7000
blazebot7000

Reputation: 129

Before attempting a custom validator, you should be able to do this with a property binding to the [min] property. Try this:

<mat-form-field appearance="legacy" [style.width.%]="45">
  <mat-label>Phasenbeginn</mat-label>
  <input matInput [max]="pEnd.value" placeholder="Beginn" [matDatepicker]="picker" formControlName="pStart">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>                                   
          
<mat-form-field appearance="legacy" [style.width.%]="45">
  <mat-label>Phasenende</mat-label>
  <input matInput [min]="pStart.value" placeholder="Ende" [matDatepicker]="picker2" formControlName="pEnd">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
 </mat-form-field>

The above code does assume that pStart and pEnd are properly implemented formControls in a formGroup. formControlName is not usable outside of a <form> with a defined [formGroup].

Upvotes: 1

Related Questions