Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple number validation using JavaScript / jQuery

Is there any simple method in JavaScript / jQuery to check whether the variable is a number or not (preferably without a plugin)? I want to alert whether the variable is a number or not.

Thanks in advance...:)

like image 279
Alfred Avatar asked Nov 28 '22 10:11

Alfred


1 Answers

I wouldn't recommend the isNaN function to detect numbers, because of the Java Script type coercion.

Ex:

isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!

You should also bear in mind that isNaN will return false (is number) for floating point numbers.

isNaN('1e1'); // is number
isNaN('1e-1'); // is number

I would recommend to use this function instead:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
like image 166
Corneliu Avatar answered Nov 30 '22 23:11

Corneliu