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
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;
}
Angular mat-datepicker adds matDatepickerParse to a form control error object if it can't parse an input string
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]],
})