How check if the variable is a number or not in javascript?

Dung Do Tien Feb 12 2020 539

Hi There,

I have a registration form, I require the user have to input their age, Age must be a number but I don't know how to check it is a number and throw warning message into form if user input invalid.

I need any suggestions. Thanks many

Have 2 answer(s) found.
  • M

    Marry Christ Apr 02 2020

    Have some ways to check

    1. Use to isNaN() function (best way)

     This function returns true if the value is not a number and false is number.

    var age = null
    isNaN(age) // return false
    
    var age = "age";
    isNaN(age) // return false
    
    var age ="20";
    isNaN(age) // return true
    
    var age = 20
    isNaN(age) // return true 

     

    2. Use to typeof to check the data type of value

    var age = 21;
    if(typeof(age) === "number"){
      // To do something here
    } 

     

    3. Use to regex to check 

    function isNumber(val) { return /^-?[\d.]+(?:e-?\d+)?$/.test(val); } 
         
    isNumber(null); // false
    isNumber("1"); // true
    isNumber(1); // true
    isNumber("123abc"); // false
    isNumber("abc"); // false
    isNumber(true); // false
    isNumber(false); // false 

     

     

  • H

    Huyền Trần thị Apr 13 2020

    @Marry Christ: thank for your answer, it all info I need to solved problem for my small app.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close