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?
Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63: Value (aka Fraction/Mantissa)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With