Validation pattern for date in DD/MM/YYYY format using angular2

前端 未结 3 433
北荒
北荒 2021-01-14 01:00

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 pa

3条回答
  •  时光说笑
    2021-01-14 01:37

    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

          
            La date d'envoi n'est pas valide
          
    

    I hope this could help.

提交回复
热议问题