I wrote a simple validator comparing two date form controls on a form group.
Simple check: the maturityDate must be > than valueDate, if not invalidate the form group.
Below is the definition of the form group:
this.datesForm = this._fb.group(
{
tradeDate: [new Date(), Validators.required],
valueDate: [new Date(), Validators.required],
maturityDate: [new Date(), [Validators.required]],
dayCount: [{value: 0, disabled: true}, Validators.required]
},
{
validator: validateMaturityDate
}
);
And here's my validator.ts
import { AbstractControl } from '@angular/forms';
export function validateMaturityDate(datesForm: AbstractControl) {
const valueDate: Date = datesForm.get('valueDate').value;
const maturityDate: Date = datesForm.get('maturityDate').value;
if (maturityDate <= valueDate) {
datesForm.setErrors({ 'validMaturity': true });
} else {
datesForm.setErrors({ 'validMaturity': false });
}
return;
}
If I select a maturity date from the datepicker that is before the value date, my expectation would have been for the form group to be invalid. But that's not the case, it keeps being valid in both cases. Am I doing something wrong?
https://i.sstatic.net/KzRJg.png https://i.sstatic.net/KEM1v.png
Update the validateMaturityDate
function to return an object related to the error or null
export function validateMaturityDate(datesForm: AbstractControl) {
const valueDate: Date = datesForm.get('valueDate').value;
const maturityDate: Date = datesForm.get('maturityDate').value;
if (maturityDate <= valueDate) {
return { 'validMaturity': true };
} else {
return null;
}
}