The error message tells you Invalid escape
(Chrome) or invalid identity escape in regular expression
(Firefox). So one or more of your escapes ("\<any-character>"
) is not right.
I removed every backslash from your Regex except for the \w
. Those are not needed, because you only need to escape characters that are special characters. As your RegEx mainly consists of a character class only special characters in character classes need to be escaped. .
, $
, *
, !
are not special characters in character classes. And the -
is not a special character, if it doesn't come first (or second after a ^
).
input {
border: 2px solid;
}
input:valid {
border-color: green;
background: rgba(0, 255, 0, 0.3);
}
input:invalid {
border-color: red;
background: rgba(255, 0, 0, 0.3);
}
With escaped <code>!<code> => <code>^[-\w.$@*\!]{1,30}</code><br>
<input pattern="^[-\w.$@*\!]{1,30}$" value="a" /> Should be valid, but throws error<br>
<input pattern="^[-\w.$@*\!]{1,30}$" value="a a " /> Should be invalid, but throws error<br>
<input pattern="^[-\w.$@*\!]{1,30}$" value="a!@@$-!...@" /> Should be valid, but throws error<br>
<br>
Without escaped <code>!<code> => <code>^[-\w.$@*!]{1,30}</code><br>
<input pattern="^[-\w.$@*!]{1,30}$" value="a" /> Should be valid<br>
<input pattern="^[-\w.$@*!]{1,30}$" value="a a " /> Should be invalid<br>
<input pattern="^[-\w.$@*!]{1,30}$" value="a!@@$-!...@" /> Should be valid<br>
Explanation
The pattern
always sets the u
flag for the RegEx. u
here means Unicode.
From: https://mathiasbynens.be/notes/es6-unicode-regex#impact-html
The u flag is always enabled for regular expressions compiled through the HTML pattern
attribute. Here’s a demo / test case.
But the Unicode flag will only allow reserved escape sequences, and \!
is not one of those as !
is never a special character.
From: https://mathiasbynens.be/notes/es6-unicode-regex#impact-syntax
things like \a
(where a
is not an escape character) won’t be equivalent to a
anymore. So even though /\a/
is treated as /a/
, /\a/u
throws an error, because \a
is not a reserved escape sequence.
P.S.: Microsoft Edge browser does seem to be Unicode capable, as this code will throw an error /\!/u
, even with the best and most telling error message of all the browsers: "invalid escape in unicode pattern", but it does not seem the set the unicode flag on pattern
attributes.