问题
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:
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}`);
}
}
来源:https://stackoverflow.com/questions/53284824/date-validation-using-angular-material-date-picker