I would like to create Custom Validators in my FormGroup for the minimum and maximum date the user can select for their DOB with the minimum as January 1st, 1900 and the maximum date as the current date. This is my current code:
export class CustomValidators {
static dateMinimum(mindate: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null) {
return null;
}
const controlDate = moment(control.value, '01/01/1990');
if (!controlDate.isValid()) {
return null;
}
const validationDate = moment(mindate);
return controlDate.isBefore(validationDate) ? null : {
'date-minimum': {
'date-minimum': validationDate.format('01/01/1990'),
'actuel': controlDate.format('01/01/1990')
}
};
};
}
static dateMaximum(maxdate: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null) {
return null;
}
const controlDate = moment(control.value, '');
if (!controlDate.isValid()) {
return null;
}
const validationDate = moment(maxdate);
return controlDate.isAfter(validationDate) ? null : {
'date-maximum': {
'date-maximum': validationDate.format(''),
'actuel': controlDate.format('')
}
};
};
}
}
export class PersonalInfoComponent implements OnInit {
peopleCoveredDOBs = new FormControl('', [Validators.required, CustomValidators.dateMaxmimum(''), CustomValidators.dateMinimum('1900-0-1')])
startDate = new FormControl('', Validators.required)
numCovered = new FormControl('', [Validators.required, Validators.max(8)])
selfCovered = new FormControl('', Validators.required)
ZIPCode = new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(5)])
personalInfoForm: FormGroup = this.builder.group({
peopleCoveredDOBs: this.peopleCoveredDOBs,
startDate: this.startDate,
numCovered: this.numCovered,
selfCovered: this.selfCovered,
ZIPCode: this.ZIPCode
});
}
Currently the dateMaximum wavlidator is not passing into the Form Control. Is there an easier way to add multiple static custom validators? I would additionally like to add a custom validator for zip code with my public badZIPSubmitted = false;