Date and Currency validation in Angular (4)

后端 未结 9 1714
没有蜡笔的小新
没有蜡笔的小新 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:53

    Here is (imo) a better date validation function:

    function date(c: AbstractControl): { [key: string]: boolean } {
       let value = new Date(c.value);
       return isNaN(value.getTime()) || value <= new Date('01/01/1753') ? {'dateInvalid': true} : undefined;
    }
    
    0 讨论(0)
  • 2021-01-01 20:57

    Angular mat-datepicker adds matDatepickerParse to a form control error object if it can't parse an input string

    0 讨论(0)
  • 2021-01-01 20:58

    If you are using reactive forms, you can write a custom validator,see below

    dateValidator(c: AbstractControl): { [key: string]: boolean } {
        let value = c.value;
        if (value && typeof value === "string") {
          let match = value.match(/^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);
          if (!match) {
            return { 'dateInvalid': true };
          } else if (match && match[0] !== value) {
            return { 'dateInvalid': true };
          }
        }
        return null;
      }
    

    While creating control, you need to add this validator along with your other validators as shown below,

    const group = this.fb.group({
        DateType: ['', [Validators.required, this.dateValidator]],
      })
    
    0 讨论(0)
提交回复
热议问题