Scott
Scott

Reputation: 505

Date validation using angular material date picker

I am trying to validate dates using the material date picker. Specifically what I am trying to validate is when the user types 'abc' into a date field I would like to show them 'please enter a valid date'. I would like to be able to do that on keystrokes so when they enter 'a' and 'ab' and 'abc' they get the same error.

The problem is the date picker appears to not set the model value and its errors until the value is able to parse to a date. I know this because the form control is not dirty and it still has an error of required when typing 'abc'.

Can this be done?

Upvotes: 2

Views: 5141

Answers (2)

Shashwat Gupta
Shashwat Gupta

Reputation: 5264

add [min] and [max] property like below code :-

i added min Date as 2020 (its mean you can not select less than 2020)
I added max Date as 7 day ahead from current date (you can not select after 7day`s ahead future date)

You can change as per your requirement , now you can get the idea to set calender validation    

   <mat-form-field class="full-width">
                <mat-label>Purchase Date</mat-label>
                <input
                  matInput
                  readonly
                  [min]="minDate" 
                  [max]="maxDate"
                  placeholder="Choose a Date"
                  (dateChange)="changeDate($event)"
                  formControlName="date_of_purchase"
                  [matDatepicker]="picker"
                />
                <mat-datepicker-toggle
                  matSuffix
                  [for]="picker"
                ></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
              </mat-form-field>
    
    
    ts
    
      minDate = new Date(2000, 0, 1);
      today = new Date();
      maxDate = new Date();
    
    constructor(
        
        private router: Router,
        
      ) {
        
        this.maxDate = new Date(this.today.setDate(this.today.getDate() + 7));
        this._fillForm();
      }

Upvotes: 0

Abhidev
Abhidev

Reputation: 7253

You can attach a handler on 'dateChange' which is triggered onChange of the input field of the mat-datepicker and validate the user input.

You can also try out 'dateInput' of mat-datepicker.

Refer https://material.angular.io/components/datepicker/api#MatDatepickerInput

Update

HTML

<input matInput [matDatepicker]="picker" placeholder="Input & change events"
     (dateInput)="addEvent('input', $event)" (dateChange)="addEvent('change', $event)" (keyup)="keyEvent('keyUp', $event)">

TS

import {Component} from '@angular/core';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';

    /** @title Datepicker input and change events */
    @Component({
      selector: 'datepicker-events-example',
      templateUrl: 'datepicker-events-example.html',
      styleUrls: ['datepicker-events-example.css'],
    })
    export class DatepickerEventsExample {
      events: string[] = [];

      addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
        this.events.push(`${type}: ${event.value}`);
      }

      keyEvent(type: string, event: KeyboardEvent) {
        this.events.push(`${type}: ${event.target.value}`);
      }
    }

Upvotes: 1

Related Questions