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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With