Skip to content
Advertisement

Angular Validator check if input is number

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?

Advertisement

Answer

+ 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;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement