I am working on creating a validator for a set of inputs in my reactive 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])],
});
/**
* Checks to make sure the start and end date selected
* are in an acceptable format.
*
* @param formGroup
*/
validateDates(formgroup: FormGroup) {
const start = formgroup.controls["effectiveStartDate"].value;
const end = formgroup.controls["effectiveEndDate"].value;
/**
* Validation Logic
* - End date cannot come before start date
* - Start date cannot come after end date
* - Start date cannot be empty
* - End Date cannot 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>
For some reason, my error isn't showing up when I leave my end date empty for example. I feel like maybe I am calling the validator incorrectly? Compose was the only method I could find for chaining together multiple validators, but I am not sure if I need to pass anything with it?
Update:
Here is my full existing form, removing the validator from the individual controls. It also shows that i currently have a validator in place for this form, perhaps incorrectly.
How could I include multiple?
this.transitionForm = this.fb.group({
changeType: ['', Validators.required],
effectiveStartDate: [this.utils.dateToISO(startDate), Validators.required],
effectiveEndDate: [(endDate ? endDate : ''), Validators.required],
},
{
// Validate to make sure we selected at least one transition field
validator: (formGroup: FormGroup) => {
return this.validateFilter(formGroup);
}
});