2

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?

1
  • Facing the same issue. Did you find a solution? Commented Feb 21, 2019 at 18:08

2 Answers 2

1

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}`);
      }
    }
Sign up to request clarification or add additional context in comments.

5 Comments

I saw that but unfortunately that is only called when the user tabs out of the field?
Here is a stack blitz. Unfortunately dateInput and dateChange only fire when it thinks it can parse a date. stackblitz.com/angular/…
updated the answer, you can make use of our traditional keyboard events.
Thanks. The keyUp event works. It ends up being clunky for us because we have a generic page validation that only triggers when a) field is dirty or b) user presses save. In this case the field is not dirty because it cannot parse. I can bypass this with boilerplate code but it starts getting ugly based on the number of places used.
Your problem statement says that you needed the validation on key strokes, right?
0
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();
      }

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.