6

How to add validation pattern for Date in DD/MM/YYYY format using angular2 Validator.pattern.

I have the "required" validator in place. Cannot find one for date pattern. Code as below:

this.txtDob = new Control("", Validators.compose([Validators.required]));
Prashanth
  • 1,235
  • 2
  • 12
  • 13

3 Answers3

3

There is no built-in date validator. You have to create a custom one http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html

Your validator will look like this https://github.com/Angular2Buch/angular2-forms/blob/master/src/app/validators/date.validator.ts

Update: You need to have class for the validator. Specify it as a second element of array in Validators.compose:

Validators.compose([Validators.required, MyValidator])

Pattern may work too: How to add form validation pattern in angular2

Community
  • 1
  • 1
Andrei Zhytkevich
  • 8,039
  • 2
  • 31
  • 45
  • Will adding this "/^\d{1,2}\.\d{1,2}\.\d{4}$/" in Validators.pattern work? Like : Validators.pattern('/^\d{1,2}\.\d{1,2}\.\d{4}$/') – Prashanth Jun 16 '16 at 13:06
2

You can create a simple custom validator as below

import {Injectable} from "@angular/core";
import {FormControl} from "@angular/forms";


@Injectable()
export class DateValidator {

  constructor() {
  }

  static date(c: FormControl) {
    const dateRegEx = new RegExp(/^\d{1,2}\.\d{1,2}\.\d{4}$/);
    return dateRegEx.test(c.value) ? null : {date: true}
  }
}

and call it in your form

senddate: new FormControl(new Date(), Validators.compose([Validators.required, DateValidator.date])),

And then simply show the error in your html

      <mat-error *ngIf="form.controls.senddate.dirty && form.controls.senddate.errors?.date">
        La date d'envoi n'est pas <strong>valide</strong>
      </mat-error>

I hope this could help.

H.abidi
  • 579
  • 1
  • 7
  • 16
0

You can also create a service( not mandatory, i.e the following could easily be changed to a regular function ) as follows:

import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';

    interface Validator<T extends FormControl> {
      (c: T): { [error: string]: any };
    }

    @Injectable()
    export class DateValidatorClass {

      constructor() { }
      dateValidator(c: FormControl) {

        const dateRegEx = new RegExp(yourRegExInHere);;

        return c.value.test(dateRegEx) ? null : {
          dateValidator: {
            valid: false
          }
    };
  }
}
Hlawuleka MAS
  • 550
  • 5
  • 11