我想在文本框中只允许整数和浮点数(最多 3 位小数),如何使用 javascript 实现这一点?
有效值为
1234
12.3
12.314
1.11
0.4
无效
1.23456
abcd or any other character
我想在文本框中只允许整数和浮点数(最多 3 位小数),如何使用 javascript 实现这一点?
有效值为
1234
12.3
12.314
1.11
0.4
无效
1.23456
abcd or any other character
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.
尝试这个:
var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));
使用正则表达式验证您的输入字段,正则 rexpression 如下
^[0-9]+(?:\.[0-9]{1,3})?$