My HTML has the following input element (it is intended to accept email addresses that end in ".com"):
<input type="email" name="p_email_ad" id="p_email_ad" value="" required="required" pattern="[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$" maxlength="64">
At some point in the past 2 months, Chrome has started returning the following JavaScript error (and preventing submission of the parent form) when validating that input:
Pattern attribute value
[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression:/[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+(\.[\-a-zA-Z0-9~!$%\^&*_=+}{\'?]+)*@([a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.([cC][oO][mM]))(:[0-9]{1,5})?$/: Invalid escape
Regex101.com likes the regex pattern, but Chrome doesn't. What syntax do I have wrong?
Use
pattern="[\-a-zA-Z0-9~!$%^&*_=+\}\{'?]+(\.[\-a-zA-Z0-9~!$%^&*_=+\}\{'?]+)*@[a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.[cC][oO][mM](:[0-9]{1,5})?"
The problem is that some chars that should not be escaped were escaped, like ' and ^ inside the character classes. Note that (, ), [, {, }, /, - and | inside a character class must now be escaped when the regex is used within the pattern attribute (and is thus compiled with the v flag).
Note also that HTML5 engines wraps the whole pattern inside ^(?: and )$ constructs, so there is no need using $ end of string anchor at the end of the pattern.
Test:
<form>
<input type="email" name="p_email_ad" id="p_email_ad" value="" required="required" pattern="[\-a-zA-Z0-9~!$%^&*_=+\}\{'?]+(\.[\-a-zA-Z0-9~!$%^&*_=+\}\{'?]+)*@[a-zA-Z0-9_][\-a-zA-Z0-9_]*(\.[\-a-zA-Z0-9_]+)*\.[cC][oO][mM](:[0-9]{1,5})?" maxlength="64">
<input type="Submit">
</form>
I have also faced the same issue in angular.
paraInputRegex = new RegExp(/^[0-9]+([+-][0-9]+)*$/);
This regex was given error in <input [pattern]="paraInputRegex">. Error stats that
Pattern attribute value /^[0-9]+([+-][0-9]+)$/ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: //^[0-9]+([+-][0-9]+)$//v: Invalid character in character class
It is because - need a escape key so the updated regex should be like paraInputRegex = new RegExp(/^[0-9]+([+\-][0-9]+)*$/);
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