Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reactive custom validator not working

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

like image 854
baouss Avatar asked Sep 02 '25 16:09

baouss


1 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

like image 86
Muhammed Albarmavi Avatar answered Sep 05 '25 05:09

Muhammed Albarmavi