使用角度材料日期选择器进行日期验证

时间:2018-11-13 15:57:11

标签: angular datepicker material

我正在尝试使用物料日期选择器来验证日期。具体来说,我要验证的是,当用户在日期字段中输入“ abc”时,我想向他们显示“请输入有效日期”。我希望能够在击键时做到这一点,因此当他们输入“ a”,“ ab”和“ abc”时,它们会得到相同的错误。

问题在于日期选择器似乎无法设置模型值及其错误,直到该值能够解析为日期为止。我知道这是因为表单控件不脏,并且在键入“ abc”时仍然存在必填错误。

可以做到吗?

2 个答案:

答案 0 :(得分:0)

您可以在'dateChange'上附加一个处理程序,该处理程序会在mat-datepicker的输入字段的onChange上触发,并验证用户输入。

您还可以尝试使用mat-datepicker的“ dateInput”。

引用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}`);
      }
    }

答案 1 :(得分: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();
      }