angular 5 validation date field using form builder

Asaf shay picture Asaf shay · Jul 5, 2018 · Viewed 13.1k times · Source

i have form and i want to validate date field on submit, i am using Form Builder, how can i do this(the angular way) ? another problem why i cant see the value published_date in the date field ? i tried to search and i can't find solution for input date field.

Answer

M Khalid Junaid picture M Khalid Junaid · Jul 5, 2018

If you could use momemt() then it will very easy to get hands on date time things and you could write your own validator as

import {AbstractControl} from '@angular/forms';
import * as moment from 'moment';

export class YourValidator {
  static dateVaidator(AC: AbstractControl) {
    if (AC && AC.value && !moment(AC.value, 'YYYY-MM-DD',true).isValid()) {
      return {'dateVaidator': true};
    }
    return null;
  }
}

And in your form object you could use it like

import {YourValidator} from "....";

this.form = this.formBuilder.group({
    title : ['', Validators.required],
    author : ['', Validators.required],
    datePublish: ['', Validators.compose([Validators.required, YourValidator.dateVaidator])],
});

Demo stackblitz.com/angular-date-validator