Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert HTML5 Regex pattern to javascript Regex

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.

like image 643
vsync Avatar asked Sep 05 '25 17:09

vsync


2 Answers

Use the RegExp constructor :

var regex = this.pattern,
    valid = new RegExp("^"+regex+"$").test( e.charCode );

But your pattern should probably be \d+, not \d*.

like image 144
Denys Séguret Avatar answered Sep 07 '25 08:09

Denys Séguret


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

like image 43
Vinay Pratap Singh Bhadauria Avatar answered Sep 07 '25 08:09

Vinay Pratap Singh Bhadauria