Currently i'm using this reg exp:
var valid = (value.match(/^\d+$/));
But for digits like '0.40', or '2.43' this doesn't work. How can I change that reg exp above to match floats as well?
Currently i'm using this reg exp:
var valid = (value.match(/^\d+$/));
But for digits like '0.40', or '2.43' this doesn't work. How can I change that reg exp above to match floats as well?
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+)?$/));
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);
}
Here's my RegExp version.
var n = /^[+-]?((\.\d+)|(\d+(\.\d+)?))$/;
Match
n.test('3');
n.test('3.0');
n.test('0.3');
n.test('.3');
n.test('+3');
n.test('+3.0');
n.test('+0.3');
n.test('+.3');
n.test('-3');
n.test('-3.0');
n.test('-0.3');
n.test('-.3');
Don't match
n.test('');
n.test('+');
n.test('-');
var valid = (value.match(/^[\d.]+$/));
This is what I use
/[\+]?([\-]?([0-9]{1,})?[\.]?[0-9]{1,})/
Here is validation without any regular expressions, using the "validity" property of the element itself:
var valid = input_element.validity.valid;
Here's a regex that accepts and captures all & only valid non-negative floats (but it doesn't handle exponents):
((?:\d+\.\d*)|(?:\d*\.?\d+))
Accepts 1, 1.0, 1., 0.1, .1 but not "." nor anything with more than one "."
See sample at regex101: https://regex101.com/r/t7eikU/1