admin管理员组文章数量:1394164
For an input field with a regex pattern:
<input type="text" maxlength="4" inputmode='numeric' pattern="\d*">
I would like to use javascript to validate the input, by parsing the pattern
attribute in some way like this (which doesn't work):
$('input').on('keypress', function(e){
var regex = this.pattern,
valid = eval(regex).test( e.charCode );
if( !valid )
return false;
});
I know the Regex in the pattern is different than the one JS uses, but I need some way to convert any Regex in a way this method could work, to allow the typing of only the chars allowed by the pattern.
For an input field with a regex pattern:
<input type="text" maxlength="4" inputmode='numeric' pattern="\d*">
I would like to use javascript to validate the input, by parsing the pattern
attribute in some way like this (which doesn't work):
$('input').on('keypress', function(e){
var regex = this.pattern,
valid = eval(regex).test( e.charCode );
if( !valid )
return false;
});
I know the Regex in the pattern is different than the one JS uses, but I need some way to convert any Regex in a way this method could work, to allow the typing of only the chars allowed by the pattern.
Share Improve this question edited Oct 18, 2013 at 11:30 vsync asked Oct 18, 2013 at 11:10 vsyncvsync 131k59 gold badges340 silver badges423 bronze badges 3-
As a rule of thumb : if your solution uses
eval
, it's probably bad. – Denys Séguret Commented Oct 18, 2013 at 11:15 - I wouldn't say BAD if it's something I use internally for myself and no injection may occur. – vsync Commented Oct 18, 2013 at 11:22
- 1 Not "BAD" as is "prone to injection" but "bad" as in "inefficient, inelegant and prone to bugs". – Denys Séguret Commented Oct 18, 2013 at 11:26
3 Answers
Reset to default 6Use the RegExp constructor :
var regex = this.pattern,
valid = new RegExp("^"+regex+"$").test( e.charCode );
But your pattern should probably be \d+
, not \d*
.
Just add the start and end of the string "^"+your reg ex here+"$"
Maybe you can use this plugin. It emulated the html5 features when they are not available (older browsers).
本文标签: convert HTML5 Regex pattern to javascript RegexStack Overflow
版权声明:本文标题:convert HTML5 Regex pattern to javascript Regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744697260a2620354.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论