Friday, April 24, 2020

Angular CLI - Custom Date validator

Angular supports of custom validators. Here i have created custom validator to validate date for template drive forms.

Directive: date-validator.directive.ts


import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
import * as moment from 'moment';
import { NG_VALIDATORS, Validator } from '@angular/forms';
import { Directive } from '@angular/core';

// validation function
function validateDateFactory(): ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = moment(c.value, 'M/D/YYYY', true).isValid();

    if (isValid) {
      return null;
    } else {
      return {
        validDate: {
          valid: false
        }
      };
    }
  }
}

@Directive({
  selector: '[validDate][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: ValidDateValidator, multi: true }
  ]
})
export class ValidDateValidator implements Validator {
  validator: ValidatorFn;

  constructor() {
    this.validator = validateDateFactory();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

}


Html:
<input type="text" [(ngModel)]="someDateModal" validDate />