Search code examples
angulardatepickerangular-material2angular-formsangular2-form-validation

How to validate mat-datepicker input using pattern?


I'm using mat-datepicker and the user is able to manually enter in a date. I would like to be able to do something like this to validate the date and make sure it follows the pattern of MM/DD/YYYY:

const dobRegex: RegExp = /((?:0[1-9])|(?:1[0-2]))\/((?:0[0-9])|(?:[1-2][0-9])|(?:3[0-1]))\/(\d{4})/;
public dob: FormControl = new FormControl(null, Validators.compose( [ Validators.required, Validators.pattern(dobRegex)]));

However, when I do the above it doesn't work because mat-datepicker is converting any input with numbers into a Date object. Any other input that aren't numbers will convert it to null.

public date(c: FormControl) {
   console.log(c.value) // This value is already a Date object or null
}

Is there a way in which I can validate the manually entered text using pattern?


Solution

  • You can solve the error by setting the minimum Value of input to be 10 characters long and the maximum value of Input to be 10 characters.Then when you enter a numeral, the date-picker will validate the date and also whether it is 10 characters long.

    Another method is by overriding the mat-date pickers parsing method by providing a custom component in your module.

    providers: [{ provide: DateAdapter, useClass: UserDateAdapter },]
    

    Then in the component

    import { NativeDateAdapter, DateAdapter } from '@angular/material';
    
    export class UserDateAdapter extends NativeDateAdapter {
    parse(value: any): Date | null {
     //Your custom parse method 
     if ((typeof value === 'string') && (value.indexOf('/') > -1) && 
          value.length == 10) {
            const str = value.split('/');
            const year = Number(str[2]);
            const month = Number(str[0]) - 1;
            const date = Number(str[1]);
            return new Date(year, month, date);
      } else {
             return new Date(undefined);
      }
    }