Date and Currency validation in Angular (4)

后端 未结 9 1716
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  -上瘾入骨i
    2021-01-01 20:39

    This is my solution:

    import {AbstractControl} from "@angular/forms";
    
    export class MyValidators {
    
      // validate MM/DD/YYYY
      static date(c: AbstractControl): { [key: string]: boolean } {
        let value = c.value;
        if (value && typeof value === "string") {
          let match = value.match(/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/);
          if (!match) {
            return {'dateInvalid': true};
          }
          let date = new Date(`${match[3]}-${match[1]}-${match[2]}`);
          if (isNaN(date.getTime())) {
            return {'dateInvalid': true};
          }
        }
        return null;
      }
    
    }
    

提交回复
热议问题