如何在反应式表单中验证日期?(角度)

时间:2019-05-27 18:56:30

标签: angular

如果日期早于今天,如何验证日期以获取错误消息。我使用了反应式表单,并且想根据在输入字段中输入的日期显示错误。我在下面附加了代码(组件html和打字稿)。我将不胜感激。

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

@Component({
  selector: 'app-cpi',
  templateUrl: './cpi.component.html',
  styleUrls: ['./cpi.component.scss']
})
export class MyComponent implements OnInit {

  public myForm: FormGroup;
  private today: Date = new Date();

  get date_cancelled() { return this.myForm.get('date_cancelled').value; }

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      emp_cancelled: [''],
      reg_employed: [''],
      date_cancelled: ['', this.dateValidator],
    });
  }

  dateValidator() {
      let from = new Date();
      let to = this.date_cancelled;
      if (from > to) {
        return false;
      }
    return true;

  }

  ngOnInit() {
    
}

}
<section class="form">
  <form [formGroup]="myForm">
        <mat-radio-group formControlName="emp_cancelled">
          <mat-radio-button value="emp_cancelled">Cancelled</mat-radio-button>
        </mat-radio-group>
        <mat-radio-group formControlName="reg_employed">
          <mat-radio-button value="reg_employed">Regularly employed</mat-radio-button>
        </mat-radio-group>
      </div>
      <br />
      <mat-form-field class="date_cancelled" *ngIf="myForm.controls.emp_cancelled?.touched">
        <input matInput [matDatepicker]="picker" placeholder="Taking effect at" formControlName="date_cancelled">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker></mat-datepicker>
      </mat-form-field>
      <mat-error *ngIf="!myForm.controls.date_cancelled?.valid">Error date</mat-error>
      <button type="submit">Submit</button>
  </form>
</section>

1 个答案:

答案 0 :(得分:1)

您可以定义自定义验证器,例如

date_cancelled: ['', (c: AbstractControl) => (new Date(c.value).getTime() < Date.now() ? { invalid: true } : null)]

还可以使用不带mat-error的{​​{1}},因为当出现验证错误时,它会自动显示/隐藏错误消息。