Ali
Ali

Reputation: 267077

Validating javascript decimal numbers

I'm using the following regexp to validate numbers in my javascript file:

var valid = (val.match(/^\d+$/));

It works fine for whole numbers like 100, 200, etc, however for things like 1.44, 4.11, etc, it returns false. How can I change it so numbers with a decimal are also accepted?

Upvotes: 7

Views: 18970

Answers (5)

Mayank
Mayank

Reputation: 958

!isNaN(text) && parseFloat(text) == text

Upvotes: 0

seanmonstar
seanmonstar

Reputation: 11444

isNaN seems like a better solution to me.

> isNaN('1')
false
> isNaN('1a')
true
> isNaN('1.')
false
> isNaN('1.00')
false
> isNaN('1.03')
false
> isNaN('1.03a')
true
> isNaN('1.03.0')
true

Upvotes: 3

Senseful
Senseful

Reputation: 91681

var valid = (val.match(/^\d+(?:\.\d+)?$/));

Matches:

 1  : yes
 1.2: yes
-1.2: no
+1.2: no
  .2: no
 1. : no

var valid = (val.match(/^-?\d+(?:\.\d+)?$/));

Matches:

 1  : yes
 1.2: yes
-1.2: yes
+1.2: no
  .2: no
 1. : no

 var valid = (val.match(/^[-+]?\d+(?:\.\d+)?$/));

Matches:

 1  : yes
 1.2: yes
-1.2: yes
+1.2: yes
  .2: no
 1. : no

var valid = (val.match(/^[-+]?(?:\d*\.?\d+$/));

Matches:

 1  : yes
 1.2: yes
-1.2: yes
+1.2: yes
  .2: yes
 1. : no

var valid = (val.match(/^[-+]?(?:\d+\.?\d*|\.\d+)$/));

Matches:

 1  : yes
 1.2: yes
-1.2: yes
+1.2: yes
  .2: yes
 1. : yes

Upvotes: 27

kennebec
kennebec

Reputation: 104780

If you want to accept decimals (including <1) and integers, with optional + or - signs, you could use valid=Number(val).

Or a regexp:

valid=/^[+\-]?(\.\d+|\d+(\.\d+)?)$/.test(val);

Upvotes: 0

hunter
hunter

Reputation: 63522

try this:

^[-+]?\d+(\.\d+)?$

Upvotes: 3

Related Questions