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
Add a ment  | 

3 Answers 3

Reset to default 6

Use 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