I'm trying to perfom form validation in Angular 9 to check if the value of a certain input is a number (integer or decimal).
I therefore created the following custom validator:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class NumberValidator {
    static number(control: AbstractControl): ValidationErrors | null {
        if (typeof +control.value === "number") return null;
        return { notANumber: "The value is not a number"};
    };
}It works fine for an integer or decimal input, telling my that it's valid, however it also tells me that the following string value for example "foo" is valid.
How can I fix that?
+ makes string as NaN which type of is number remove it. or  if u have to check one more plus of number then
 if (typeof +control.value === "number" && !isNaN(+control.value)) return null;
"+" convert variable to number ( +control.value )
So in your example you convert control.value to the number, and then check if this variable is a number. In this way it will be always a number
You need to check:
if Number(control.value) == NaN 
// returns true if control.value is string
// else returns parsed number
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