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.
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+"$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With