How to validate digits (including floats) in javascript
Continuing with the @Crescent Fresh approach, some time ago, I had to do number validation, but I needed to verify if a variable contained a number without knowing its type, it could be a String
containing a numeric value as in this case, (I had to consider also exponential notation, etc.), a Number
object, basically anything I couldn't make any type assumption.
And I had to take care about implicit type conversion, for example as I pointed to @Crescent, isNaN
wasn't enough for my case:
// string values
!isNaN(' ') == true;
!isNaN('\t\t') == true;
!isNaN('') == true;
// boolean values
!isNaN(true) == true;
!isNaN(false) == true;
// etc..
I ended up writing a set of 30+ unit tests that you can find and run here, and the following function, is the one that passes all my tests:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
You don't need regex for this! isNaN
will cast thine value to Number
:
var valid = !isNaN(value);
Eg:
!isNaN('0'); // true
!isNaN('34.56'); // true
!isNaN('.34'); // true
!isNaN('-34'); // true
!isNaN('foo'); // false
!isNaN('08'); // true
Reluctant Edit (thanks CMS):
Blasted type coercion, !isNaN('')
, !isNaN(' ')
, !isNaN('\n\t')
, etc are all true
!
Whitespace test + isNaN
FTW:
var valid = !/^\s*$/.test(value) && !isNaN(value);
Yuck.
var valid = (value.match(/^-?\d*(\.\d+)?$/));