Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 630
Platus Avatar asked Oct 28 '25 08:10

Platus


2 Answers

+ 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;
like image 141
mr. pc_coder Avatar answered Oct 31 '25 00:10

mr. pc_coder


"+" 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
like image 35
kompaniietst Avatar answered Oct 31 '25 01:10

kompaniietst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!