How check if the variable is a number or not in javascript?
Dung Do Tien Feb 12 2020 517
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.
- M2
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
- H0
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.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.