【发布时间】:2011-12-23 10:13:59
【问题描述】:
我想限制用户输入特定范围内的值。所以我使用 JQuery 1.7.1 编写了以下代码
var reg = /^[0-9]{1,4}[.]{0,1}[0-9]{0,2}$/g;
$("#txt" + filterID).bind('keypress', function (e) {
var nn = $("#txtValues");
var strValue = nn[0].value.toString();
strValue = $.trim(strValue);
var bool = reg.test(strValue);
if (strValue.length == 0 && !((e.which < 48 || e.which > 57) && e.which != 46 && e.which != 8 && e.which != 0)) {
return true;
}
else if (bool) {
return true;
}
else {
e.preventDefault();
}
});
当我测试输入框时,它没有按预期工作。它应该允许小数点后 2 位的浮点数。一些有效的格式是
1
1.
1.0
0
1.20
0.0
1.23
123.43
1234.12
我不确定,我在哪里做错了。在认识到 1. 它失败了。有人可以帮我确定问题吗?
【问题讨论】:
-
什么没有按预期工作?您在此处命名的有效数字正是您在正则表达式中定义的数字。
-
你要求有一个分数并且它有两位数吗?
-
当我以 HTML 形式测试文本框时,它允许 '1.',然后它不允许任何其他数字,它应该允许。
标签: jquery regex validation jquery-plugins