使用角度材料日期选择器进行日期验证 [英] Date validation using angular material date picker
问题描述
我正在尝试使用材料日期选择器验证日期.具体来说,我要验证的是当用户在日期字段中键入abc"时,我想向他们显示请输入有效日期".我希望能够在击键时执行此操作,因此当他们输入a"、ab"和abc"时,他们会收到相同的错误.
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.
问题是日期选择器似乎不会设置模型值及其错误,直到该值能够解析为日期.我知道这一点是因为表单控件并不脏,并且在键入abc"时仍然出现 required 错误.
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'.
这能做到吗?
推荐答案
您可以在 'dateChange' 上附加一个处理程序,该处理程序由 mat-datepicker 的输入字段的 onChange 触发并验证用户输入.
You can attach a handler on 'dateChange' which is triggered onChange of the input field of the mat-datepicker and validate the user input.
您也可以尝试使用 mat-datepicker 的dateInput".
You can also try out 'dateInput' of mat-datepicker.
参考 https://material.angular.io/components/datepicker/api#MatDatepickerInput
更新
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}`);
}
}
这篇关于使用角度材料日期选择器进行日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!