0

I'm new to angular material 2, and trying to validate the Date of Birth(DOB) form field like following example in Official Angular Website

So in input-errors-example.html I added form field like following

  <md-form-field class="example-full-width">
    <input mdInput [mdDatepicker]="picker" placeholder="Choose a date" [formControl]="dobFormControl" onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 47' maxlength="10">
    <md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
    <md-datepicker #picker></md-datepicker>
    <md-error *ngIf="dobFormControl.hasError('required') || dobFormControl.hasError('pattern')">
      Please enter a valid Date
    </md-error>
  </md-form-field>

then in input-errors-example.ts file I added custom regular expression to accept MM/DD/YYYY format

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

const DOB_REGEX = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;

@Component({
  selector: 'input-errors-example',
  templateUrl: 'input-errors-example.html',
  styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {


    dobFormControl = new FormControl('', [
        Validators.required,
        Validators.pattern(DOB_REGEX)
    ]);

} 

This is the Plunker for above example, but here I cannot select a date or cannot see any error message.

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
Kelum
  • 1,745
  • 5
  • 24
  • 45
  • 1
    The problem is that datePicker produces a `Date` object, and not a string. You shouldn't need a DOB_REGEX for it since only valid dates are selectable, instead you'll just want to pipe the date into `MM/DD/YYYY`. Check out this question for an example on formatting datepicker items: https://stackoverflow.com/questions/46118812/angular-material-datapicker-different-format-after-submit-a-form/46119492#46119492 – Z. Bagley Sep 11 '17 at 16:28

1 Answers1

1

For your FormControl to work with your regex, you have to instantiate the FormControl with null instead of '' empty string:

dobFormControl = new FormControl(null, [
        Validators.required,
        Validators.pattern(DOB_REGEX)
    ]);

Your working now plunker here

BogdanC
  • 2,746
  • 2
  • 24
  • 22