将HTML5正则表达式模式转换为javascript正则表达式

vsy*_*ync 3 javascript regex validation html5

对于带有正则表达式模式的输入字段:

<input type="text" maxlength="4" inputmode='numeric' pattern="\d*">

我想使用javascript通过pattern以这种方式解析属性(不起作用)来验证输入:

$('input').on('keypress', function(e){
    var regex = this.pattern,
        valid = eval(regex).test( e.charCode );

    if( !valid )
        return false;
});
Run Code Online (Sandbox Code Playgroud)

我知道模式中的Regex与JS使用的正则表达式不同,但是我需要某种方法以这种方法可以工作的方式转换任何Regex,以仅键入模式允许的字符。

Den*_*ret 5

使用RegExp构造函数:

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

但是您的模式应该是\d+,不是\d*