Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate digits (including floats) in javascript

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?

like image 655
Ali Avatar asked Dec 02 '09 03:12

Ali


People also ask

Is numeric JavaScript validation?

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.

What is float in JavaScript?

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)


1 Answers

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.

like image 169
Crescent Fresh Avatar answered Oct 11 '22 13:10

Crescent Fresh