Javascript 中动态 RegExp 构造的问题
此方法是为了防止用户输入除数字和“允许的字符”之外的任何内容。允许的字符作为参数 allowedchars
传递。
到目前为止,该方法阻止数字输入,但允许的字符不起作用(尝试传递“-”(连字符)和“.”(句点))。所以我假设我的动态正则表达式构造不正确。帮助?
提前致谢!
numValidate : function (evt, allowedchars) {
var theEvent, key, regex,
addToRegex = allowedchars;
theEvent = evt || window.event;
key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = new RegExp('/^[0-9' + addToRegex + ']$/');
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
}
}
(ps. jQuery 解决方案也很好)
This method is to prevent users from entering anything but numbers and "allowed characters." Allowed characters are passed as the parameter allowedchars
.
So far, the method prevents number entries but the allowedchars doesn't work (tried with passing "-" (hyphen) and "." (period)). So I'm assuming my dynamic regex construction isn't correct. Help?
Thanks in advance!
numValidate : function (evt, allowedchars) {
var theEvent, key, regex,
addToRegex = allowedchars;
theEvent = evt || window.event;
key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = new RegExp('/^[0-9' + addToRegex + ']$/');
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
}
}
(ps. jQuery solutions are fine too)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1. 当您通过
new RegExp
构造时,无需包含周围的/
。3.,但是由于您无论如何都要检查 1 个字符,因此避免正则表达式可能会更容易。
);2. 但是,如果
addToRegex
包含]
或-
,则生成的正则表达式可能会变得无效或匹配过多。因此,您需要转义它们:3.,但是由于您无论如何都要检查 1 个字符,因此避免正则表达式可能会更容易。
1. When you construct via
new RegExp
, there's no need to include the surrounding/
s.3. But since you are checking against 1 character anyway, it may be easier to avoid regex.
);2. But if
addToRegex
contains]
or-
, the resulting regex may become invalid or match too much. So you need to escape them:3. But since you are checking against 1 character anyway, it may be easier to avoid regex.