Date and Currency validation in Angular (4)

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


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!