Date validation using angular material date picker

前端 未结 1 1298
一生所求
一生所求 2021-01-24 14:54

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 th

相关标签:
1条回答
  • 2021-01-24 15:23

    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}`);
          }
        }
    
    0 讨论(0)
提交回复
热议问题