4

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.

3
  • As a rule of thumb : if your solution uses eval, it's probably bad. 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. 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". Commented Oct 18, 2013 at 11:26

3 Answers 3

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*.

Sign up to request clarification or add additional context in comments.

2 Comments

it's always false for me when i tried it... function testChar(pattern, s){ return valid = new RegExp("^"+pattern+"$").test( s ); }; testChar("\d+", '3')
That's because you badly create the string literal : use "\\d+" instead of "\d+". See jsfiddle.net/QK96C
1

Just add the start and end of the string "^"+your reg ex here+"$"

Comments

0

Maybe you can use this plugin. It emulated the html5 features when they are not available (older browsers).

1 Comment

i'm looking for a minimal solution to this, like a one-line thing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.