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.