Date and Currency validation in Angular (4)

后端 未结 9 1712
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 20:28

I am new to Angular. I am using angular 4 reactive forms and figured out how to perform custom validations. Following is my implementation for numeric

functi         


        
9条回答
  •  生来不讨喜
    2021-01-01 20:35

    This is another option to using Custom validators

    import { FormControl } from '@angular/forms';
    
    export class DateValidator {
    
       static ptDate(control: FormControl): { [key: string]: any } {
           let ptDatePattern =  /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;
    
           if (!control.value.match(ptDatePattern))
               return { "ptDate": true };
    
           return null;
       }
    
       static usDate(control: FormControl): { [key: string]: any } {
           let usDatePattern = /^02\/(?:[01]\d|2\d)\/(?:19|20)(?:0[048]|[13579][26]|[2468][048])|(?:0[13578]|10|12)\/(?:[0-2]\d|3[01])\/(?:19|20)\d{2}|(?:0[469]|11)\/(?:[0-2]\d|30)\/(?:19|20)\d{2}|02\/(?:[0-1]\d|2[0-8])\/(?:19|20)\d{2}$/;
    
           if (!control.value.match(usDatePattern))
               return { "usDate": true };
    
           return null;
       }
    }
    

    and use it this way for "dd/mm/yyyy" format:

    this.formDetail = this.formBuilder.group({
       date: ['', DateValidator.ptDate],
    });
    

    and use it this way for "mm/dd/yyyy" format:

    this.formDetail = this.formBuilder.group({
       date: ['', DateValidator.usDate],
    });
    

    I hope this help!

提交回复
热议问题