angulardateangular-reactive-formsangular-validator

Custom validator for date before in angular


I want to write a custom dateValidator with reactive forms to check if an inputed date is before today.

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]
    });
  }

What can write here? I would like the value of the input to be lower than today : value < new Date()

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

Solution

  • Since you are asking for the ValidationFn syntax, it may look like this:

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

    Usage:

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

    With moment library:

    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;
    }