Miguelit0
Miguelit0

Reputation: 115

Datepicker Angular Material filter validation

Could someone guide me to (if possible) how to prevent the user from booking certain dates?

I manage to prevent clicking on the previous dates and the end date of the contract but not the dates of unavailability. enter image description here

In my database I store dates (start date, end date) for employees.

How can I prevent the user from clicking dates when he wants to book a session with one of my employees?

Thank you!

Upvotes: 2

Views: 4886

Answers (2)

Krishna Rathore
Krishna Rathore

Reputation: 9687

You can use [min] and [max] for this.

Component.html

<mat-form-field class="example-full-width">
  <input matInput [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-form-field>

Component.ts

minDate = new Date(2000, 0, 1);
maxDate = new Date(2020, 0, 1);

Upvotes: 2

Akj
Akj

Reputation: 7231

Use [matDatepickerFilter]="myFilter"

DEMO

myFilter = (d: Date): boolean => {

        let date: any;
        let month: any;

        if (d.getDate().toString().length < 2) {
            date = '0' + d.getDate().toString()
        } else {
            date = d.getDate().toString()
        }

        if ((d.getMonth() + 1).toString().length < 2) {
            month = '0' + (d.getMonth() + 1).toString()
        } else {
            month = (d.getMonth() + 1).toString()
        }

        const day = d.getFullYear().toString() + "-" + month + "-" + date;

        return !this.disableDateList.includes(day);
    }

HTML:

<mat-form-field class="col-md-6">
     <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" formControlName="date"
                        placeholder="Choose date">
          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
          <mat-datepicker picker touchUi="true"></mat-datepicker>
  </mat-form-field>

Upvotes: 2

Related Questions