Search code examples
angularangular-reactive-forms

reactive form custom validator get called but not displaying the error in angular


The custom validator get called but errors are not displaying.

The JS portion of the form is:

this.form = this.fb.group(
      {
        article:'',
        onlyNotInProposal: false,
        ruleEnabled: false,
        minimum: [
          {
            value: 0,
            disabled: true,

          }
        ],
        maximum: [
          {
            value: null,
            disabled: true
          }]
      },
      { validators: stockThresholdValidator }
    );

The validator code is:

import { FormGroup, ValidatorFn } from '@angular/forms';

import { greaterThanValidator } from '@g3p/shared/validators/greater-than/greater-than.validator';

export const stockThresholdValidator: ValidatorFn = (formGroup: FormGroup) => {
  if (!formGroup.controls.ruleEnabled) {
    return null;
  }
  if (formGroup.controls.ruleEnabled.value) {
    return greaterThanValidator('minimum', 'maximum')(formGroup);
  }
  return null;
};

greaterThanValidator code:

import { AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';

export function greaterThanValidator(minControlName: string, maxControlName: string): ValidatorFn {
  return (formGroup: FormGroup): ValidationErrors | null => {
    const min: AbstractControl = formGroup.get(minControlName);
    const max: AbstractControl = formGroup.get(maxControlName);
    if (!min || !max) {
      return { missingControl: true };
    }
    if ((min.value !== 0 && !min.value) || (max.value !== 0 && !max.value)) {
      return { missingValue: true };
    }
    if (isNaN(min.value) || isNaN(max.value)) {
      return { onlyNumbersRequired: true };
    }
    if (min.value >= max.value) {
      return { greaterThan: true };
    }
    return null;
  };
}

I have spent a lot of time but I am not able to figure out what is wrong. If someone knows then please let me know. Thank you


Solution

  • You have set ruleEnabled: false which prevents greaterThanValidator() from being called. However, if you did set it true later in the template. There could be an issue if you forgot to add type=number for minimum and maximum fields. By default, you will get back strings so the below check

    if (min.value >= max.value) {
    

    will be comparing strings lexicographically, not numerically.

    I've created a sample app with the information you provided and see that the code works fine.

    Sample App onStackblitz

    Demo

    enter image description here