Search code examples
angularangular7customvalidator

Angular Custom validator: why export function?


I'm doing my first steps in Angular and had to make a custom maximum validator for a number field in a template form. This is it:

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, ValidatorFn} from '@angular/forms';

@Directive({
  selector: '[appMaximumValue]',
  providers: [{provide: NG_VALIDATORS, useExisting: MaximumValueDirective, multi: true}]
})
export class MaximumValueDirective implements Validator {
  @Input('appMaximumValue') maximumValue: number;

  constructor() {
  }

  validate(control: AbstractControl): ValidationErrors | null {
    return this.maximumValue ? maximumValueValidator(this.maximumValue)(control) : null;
  }
}

export function maximumValueValidator(minimum: number): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    return control.value > minimum ? {'maximumValue': {value: control.value}} : null;
  };
}

After thinking about it I discovered that it also works without the export function:

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, ValidatorFn} from '@angular/forms';

@Directive({
  selector: '[appMaximumValue]',
  providers: [{provide: NG_VALIDATORS, useExisting: MaximumValueDirective, multi: true}]
})
export class MaximumValueDirective implements Validator {
  @Input('appMaximumValue') maximumValue: number;

  constructor() {
  }

  validate(control: AbstractControl): ValidationErrors | null {
    return Number(control.value) > this.maximumValue ? {'maximumValue': {value: control.value}} : null;
  }
}

So my question is, what is the reason for this export function?


Solution

  • Because you export the maximumValueValidator, you can also use the validator logic directly inside TS files by importing the function.

    The directive can only be used in HTML files, so for the use of your form it will do without the export.

    If you want to use the validation inside your TS files for some reason, you can if you export the maximumValueValidator function since this is the real logic of your validator.

    If you are not planning to do this validation in your TS files as well, you can remove the export for maximumValueValidator.