I am currently developing a custom validator for a group of inputs within my dynamic form.
this.transitionForm = this.fb.group({
effectiveStartDate: [this.utils.dateToISO(startDate), Validators.compose([Validators.required, this.validateDates])],
effectiveEndDate: [(endDate ? endDate : ''), Validators.compose([Validators.required, this.validateDates])],
});
/**
* Ensures that the selected start and end dates are valid.
*
* @param formGroup
*/
validateDates(formgroup: FormGroup) {
const start = formgroup.controls["effectiveStartDate"].value;
const end = formgroup.controls["effectiveEndDate"].value;
/**
* Validation Rules
* - End date should not be before the start date
* - Start date should not be after the end date
* - Start date should not be empty
* - End Date should not be empty
*/
if ((end < start) || (start > end) || !start || !end) {
return { invalidDates: true };
} else {
return null;
}
}
HTML:
<div *ngIf="!transitionForm.controls['effectiveEndDate'].valid">
<p *ngIf="transitionForm.controls['effectiveEndDate'].errors.invalidDates">
Invalid End Dates
</p>
</div>
When I leave the end date field empty, the error message is not displaying. I suspect that I might be invoking the validator incorrectly. I used the `compose` method to combine multiple validators, but I am unsure if I need to pass any parameters with it.
Update:
Below is the complete current form code without the individual control validators. It also demonstrates that there is already a form-level validator set up, possibly incorrectly.
How can I incorporate multiple validators?
this.transitionForm = this.fb.group({
changeType: ['', Validators.required],
effectiveStartDate: [this.utils.dateToISO(startDate), Validators.required],
effectiveEndDate: [(endDate ? endDate : ''), Validators.required],
},
{
// Ensure at least one transition field is selected
validator: (formGroup: FormGroup) => {
return this.validateFilter(formGroup);
}
});