0

我想在文本框中只允许整数和浮点数(最多 3 位小数),如何使用 javascript 实现这一点?

有效值为

1234
12.3
12.314
1.11
0.4

无效

1.23456
abcd or any other character 
4

4 回答 4

2

根据您还需要匹配的注释,您需要".1"在正则表达式的第一部分添加条件。

var re = /^(\d+)?(?:\.\d{1,3})?$/;

粗略的测试套件 - jSFiddle

于 2013-03-22T12:25:08.833 回答
0

You can use a regular expression to do this:

/^\d+(?:\.\d{1,3})?$/

That's the start of the string (^), one or more digits (\d+), optionally followed by a . and between 1 and 3 digits ((?:\.\d{1,3})), then the end of the string ($).

To compare it to the value of an input, you'd do something like this:

var re = /^\d+(?:\.\d{1,3})?$/;
var testValue = document.getElementById('id-of-input').value;
if(re.test(testValue)) {
    // matches - input is valid
}
else {
    // doesn't match - input is invalid
}

Take a look at this jsFiddle demo.

于 2013-03-22T11:55:11.820 回答
0

尝试这个:

var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));

检查小提琴 http://jsfiddle.net/8mURL/1

于 2013-03-22T11:58:11.967 回答
0

使用正则表达式验证您的输入字段,正则 rexpression 如下

^[0-9]+(?:\.[0-9]{1,3})?$
于 2013-03-22T11:49:56.900 回答