Date and Currency validation in Angular (4)

与世无争的帅哥 提交于 2019-12-04 00:51:42

问题


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

function numberValidator(c: AbstractControl): { [key: string]: boolean } | null {
    if (c.pristine) {
        return null;
    }
    if (c.value.match(/.*[^0-9].*/)) {
        return { 'numeric': true };
    }
    return null;
}

 phoneControl: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10), numberValidator]],

I am trying to find out how to perform currency (with or without two decimal places) and most importantly Date field.

Forgive me if this was answered elsewhere but I cannot find any samples for angular(4)

Thanks for your time


回答1:


What kind of date validation do you need? Just that the value is a valid date? If you set the type="date" on the input element the browser will ensure that only a valid date is entered.

Same for your shown number validator and for any currency validator. You should be able to set the type="number" on the input element and you won't need a validator.

If you still do want to perform your own validation, you can use regular expressions just as in your example.

Just look up regular expressions for currency and date. For the date, something like this: Javascript - Regex to validate date format




回答2:


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!




回答3:


Created a custom validator to handle formats MM/DD/YYYY and MMDDYYYY

function dateValidator(c: AbstractControl): { [key: string]: boolean } | null {
    if (c.pristine) {
        return null;
    }
    if ((c.value !== undefined && c.value !== '' && c.value != null)) {

        var month = null;
        var day = null;
        var year = null;
        var currentTaxYear = Number(new Date().getFullYear() - 1);
        if (c.value.indexOf('/') > -1) {
            var res = c.value.split("/");           
            if (res.length > 1) {
                month = res[0];
                day = res[1]
                year = res[2];
            }                              
        }
        else {
            if (c.value.length == 8) {
                month = c.value.substring(0, 2);
                day = c.value.substring(2, 4);
                year = c.value.substring(4, 8);
            }            
        }
        if (isNaN(month) || isNaN(day) || isNaN(year)) {
            return { 'dateInvalid': true };
        } 
        month = Number(month);
        day = Number(day);
        year = Number(year);
        if (month < 1 || month > 12) { // check month range
            return { 'dateInvalid': true };
        }
        if (day < 1 || day > 31) {
            return { 'dateInvalid': true };
        }
        if ((month === 4 || month === 6 || month === 9 || month === 11) && day === 31) {
            return { 'dateInvalid': true };
        }
        if (month == 2) { // check for february 29th
            var isleap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
            if (day > 29 || (day === 29 && !isleap)) {
                return { 'dateInvalid': true };
            }
        }
        if (year !== currentTaxYear) {
            return { 'dateYearGreaterThanTaxYear': true };
        }
    }
    return null;
}



回答4:


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;
  }

}



回答5:


If you're using Angular Material, you can use the MatDatepicker integration with Moment.js to validate a custom date format using FormControl as shown here:

https://material.angular.io/components/datepicker/overview#customizing-the-parse-and-display-formats

HTML:

<input matInput [matDatepicker]="dp" placeholder="Verbose datepicker" [formControl]="date">

TS:

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'datepicker-formats-example',
  templateUrl: 'datepicker-formats-example.html',
  styleUrls: ['datepicker-formats-example.css'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerFormatsExample {
  date = new FormControl(moment());
}



回答6:


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]],
  })


来源:https://stackoverflow.com/questions/46589865/date-and-currency-validation-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!