Angular reactive custom validator not working

Viewed 6191

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.stack.imgur.com/KzRJg.png https://i.stack.imgur.com/KEM1v.png

2 Answers

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;
    }
}

ValidatorFn interface

The answer from malbarmawi is spot on. This question was exactly the same scenario for which I couldn't get the formGroup validator to execute and spun my wheels for hours.

However in my case I had listed the validator in the FormGroup under a key called validators instead of validator.

This is correct: { validator: validateMaturityDate } This doesn't execute: { validators: validateMaturityDate }

The angular.io documentation here shows validators as plural. So either I'm missing something or the documentation might need a tweak.

https://v6.angular.io/guide/form-validation#cross-field-validation

Related