Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper return value for a ValidatorFn function in Angular?

I have the following code in my custom validator:

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

// Credit for this function:
// https://stackoverflow.com/a/17390131/2044
function isPrime(aNumber: number): boolean {
  let start: number = 2;
  const limit: number = Math.sqrt(aNumber);
  while (start <= limit) {
    if (aNumber % start++ < 1) {
      return false;
    }
  }
  return aNumber > 1;
}

export class NumberValidators {
  static isPrimeNumber(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (isPrime(control.value)) {
        return null;
      }
      return {
        isPrimeNumber: true
      };
    };
  }

This code works; however, it seems backwards to me. It seems like the if statement is 180 degrees out -- that it should return the object (with true) when the value validates and null when it doesn't.

So my question is: What is going on here?

like image 691
Nick Hodges Avatar asked Oct 15 '25 03:10

Nick Hodges


1 Answers

I'll admit the return value for a validator looks a bit funky but the docs have all the information on it you need: https://angular.io/api/forms/ValidatorFn

A function that receives a control and synchronously returns a map of validation errors if present, otherwise null.

Just by definition a validator function returns null when there is no error. Else, it returns an object where the error is defined by the key.

That's also exactly what this method signature is saying:

(control: AbstractControl): { [key: string]: any } | null 

This validator function takes in a input of type abstract control and will return EITHER an object where the key is a string and the value is of type any OR null. The type any in case of an error allows you to provide more context regarding the error. For example max validator returns the following object upon error {max: {max: 15, actual: 16}} which can further be used to provide a user friendly error message

like image 110
Crhistian Avatar answered Oct 17 '25 17:10

Crhistian