使用角度材料日期选择器进行日期验证 [英] Date validation using angular material date picker

查看:75
本文介绍了使用角度材料日期选择器进行日期验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用物料日期选择器来验证日期.具体来说,我要验证的是,当用户在日期字段中输入"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"时仍然存在必填错误.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆