angular 之前日期的自定义验证器

Custom validator for date before in angular

我想写一个自定义 dateValidator 反应形式来检查输入的日期是否在今天之前。

Component.html

<form class="container" [formGroup]="form" (ngSubmit)="submit()">
  <div mat-dialog-content>
    ...
    <mat-form-field>
      <mat-label>Birthday</mat-label>
      <input  matInput [matDatepicker]="birthdayDatepicker" formControlName="birthday">
      <mat-datepicker-toggle matSuffix [for]="birthdayDatepicker"></mat-datepicker-toggle>
      <mat-datepicker #birthdayDatepicker></mat-datepicker>
    </mat-form-field>
  </div>
</form>

Component.ts

  ngOnInit() {
    this.form = this.fb.group({
      name : [,Validators.required],
      email: [,Validators.email],
      birthday: [,dateValidator],
      role: [,Validators.required]
    });
  }

这里可以写什么?我希望输入值低于今天: value < new Date()

export function dateValidator(): ValidatorFn {
  ...
}

您可以看到 Stackblitz demo here.

export function dateValidator(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const today = new Date().getTime();

    if(!(control && control.value)) {
      // if there's no control or no value, that's ok
      return null;
    }

    // return null if there's no errors
    return control.value.getTime() > today 
      ? {invalidDate: 'You cannot use future dates' } 
      : null;
  }
}

你可以这样使用:

ngOnInit() {
    this.form = this.fb.group({
      ...
      birthday: [new Date(), dateValidator()],
      ...
    });
  }

由于您要求的是 ValidationFn 语法,因此它可能如下所示:

dateValidator(control: FormControl): { [s: string]: boolean } {
    // implementation of the validation
}

用法:

ngOnInit() {
  this.form = this.fb.group({
    name : [,Validators.required],
    email: [,Validators.email],
    birthday: [,this.dateValidator],
    role: [,Validators.required]
  });
}

使用 moment 库:

import * as moment from 'moment';

[...]

dateValidator(control: FormControl): { [s: string]: boolean } {
  if (control.value) {
    const date = moment(control.value);
    const today = moment();
    if (date.isBefore(today)) {
      return { 'invalidDate': true }
    }
  }
  return null;
}