角材料日期验证器获取无效值

时间:2018-08-01 12:13:53

标签: angular

{{1}}

亲爱的

我试图在日期字段中输入日期值“ 1”,但是dateValidator中的control.value返回2001-01-01 GMT 00:00。即使我在日期字段中填写了“ 1”,它也使dateValidator始终传递。如何从“ control.value”获取原始值“ 1”,而不是自动转换的值?谢谢

2 个答案:

答案 0 :(得分:1)

发生这种情况的原因是因为其DatePicker输入上的材料registers an input listener

_onInput(value: string) {
  let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);

parse()方法does this

parse(value: any): Date | null {
  if (typeof value == 'number') {
    return new Date(value);
  }

因此,当用户在您的输入中写入1时,它就会在后台变成new Date(1)

所以要回答您的问题-“如何从“ control.value”中获取原始值“ 1” ,则可以覆盖inputchange事件:

<input matInput 
       [(ngModel)]="myDate" 
       name="myDate" [matDatepicker]="Datepicker"
       (click)="Datepicker.open()" 
       (input)="someMethod($event.target.value)" 
       (change)="someMethod($event.target.value)">

答案 1 :(得分:0)

尝试这样:

Live Example

HTML:

<h1>
    Try Reactive Form Validation with custom validation
</h1>

<form [formGroup]="basicForm">
    <div>
        <input type="text" formControlName="myDate" />
        <p *ngIf="basicForm.get('myDate').hasError('required') && basicForm.get('myDate').touched">Required</p>
        <p *ngIf="basicForm.get('myDate').hasError('invalidDate')">Invalid Date DD/MM/YYYY</p>
    </div>
</form>

TS:

 basicForm: FormGroup;


  ngOnInit() {
    this.createForm();
  }

  constructor(private fb: FormBuilder) {
  }

  createForm() {
    this.basicForm = this.fb.group({

      myDate: [null, [Validators.required, CustomValidatorService.dateValidator]]
    })
  }

validation_service.ts:

import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';

@Injectable()
export class CustomValidatorService {

  constructor() { }

  static dateValidator(control: FormControl) {
    if (control.value) {
      const matches = control.value.match(/^\d{2}\/\d{2}\/\d{4}$/);
      return matches ? null : { 'invalidDate': true };
    } else {
      return null;
    }
  }
}
相关问题