admin管理员组

文章数量:1180547

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?

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?

Share Improve this question asked Mar 22, 2010 at 20:16 AliAli 267k267 gold badges590 silver badges784 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 27
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

try this:

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

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

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);

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

本文标签: jqueryValidating javascript decimal numbersStack Overflow