使用 JQuery 进行正则表达式验证的问题
我想限制用户输入特定范围内的值。所以我使用 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.它失败了。有人可以帮我找出问题所在吗?
I wanted to restrict the user from entering the values from a specific range. So i wrote the following code using 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();
}
});
When i test the input box, it's not working as expected. It supposed to allow a floating point number with 2 digits after decimal point.Some of the valid formats are
1
1.
1.0
0
1.20
0.0
1.23
123.43
1234.12
I am not sure, where I have done wrong. After recognizing 1. it's getting failed. Can anybody help me to identify the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
keypress
事件在值更新之前触发。使用以下代码,该代码使用String.fromCharCode
方法将event.which
属性转换为字符。不可打印的击键将生成一个为零的
event.which
,这当然不是数字或点。对于正则表达式,您必须将点后面的表达式分组,并添加一个问号,表示“让该组匹配是可选的”。
该模式将匹配以下内容:
The
keypress
event is fired before the value has updated. Use the following code, which translates theevent.which
property to a character using theString.fromCharCode
method.Non-printable keystrokes will generate a
event.which
of zero, which is certainly not a digit or dot.As for the RegExp, you have to group the expression after the dot, and add a questionmark, to say "Let this group match be optional".
The pattern will match the following:
表达式
{0,1}
和{0,2}
中的间隔运算符允许组重复 0 到 1 次,或分别重复 0 到 2 次,这允许使用小数和整数。此外,您还应该指定文字点\.
而不仅仅是点,它可以匹配任何字符。如果您想强制使用小数点后 2 位数字,请尝试将间隔限制为 {2} 并将其与点一起捆绑到一组中,例如
/^[0-9]{1,4}(\.{1}[0-9]{2})$/
The interval operators in your expression
{0,1}
and{0,2}
allow for a group to be repeated 0 to 1, or respectively 0 to 2 times, which allows for decimal numbers as well as integers. Also you should specify the literal dot\.
instead of just the dot, which matches any character.If you want to enforce numbers with 2 digits after the decimal, try restricting your interval to {2} and bundle it into a group together with the dot, e.g.
/^[0-9]{1,4}(\.{1}[0-9]{2})$/