I am trying to make an <input>
field that uses a pattern to check if the input is a valid windows file path.
The pattern I have is
/^(?:[\w]\:|\\)(\\[a-zA-Z_\-\s0-9\.()~!@#$%^&=+';,{}\[\]]+)+\.(exe)$/g
However, when putting this into the pattern attribute of an <input>
field:
<input id="path" type="text" pattern="^(?:[\w]\:|\)(\[a-zA-Z_\-\s0-9\.()~!@#$%^&=+';,{}[]]+)+\.(exe)$">
An error is displayed in the console saying:
Pattern attribute value
^(?:[\w]\:|\\)(\\[a-zA-Z_\-\s0-9\.()~!@#$%^&=+';,{}\[\]]+)+\.(exe)$ is
not a valid regular expression: Uncaught SyntaxError: Invalid regular
expression: /^(?:[\w]\:|\\)(\\[a-zA-Z_\-\s0-9\.()~!@#$%^&=+';,{}\[\]]+)+\.(exe)$/:
Invalid escape
I have tried several ways of writing this pattern, but none seem to work.
You only need to escape the characters in the character class that must be escaped otherwise, you will always get this error.
2023 Update:
Now, that pattern
attribute is compiled with the v
flag, escaping rules have become way stricter. See Valid with the RegExp u flag, but not with the v flag for more details.
The current solution will look like
pattern="(?:\w:|\\)(\\[\w\s.\(\)~!@#$%^&=+';,\{\}\[\]\-]+)+\.exe"
Note the [
, {
, }
, (
and )
that are escaped now.
Original answer
Use
pattern="(?:\w:|\\)(\\[\w\s.()~!@#$%^&=+';,{}[\]-]+)+\.exe"
See the JSFiddle
Details:
]
inside the character class must be escaped[
and .
must not be escaped:
must never be esacaped, it is never a special character[a-zA-Z0-9_]
= \w
pattern
is always anchored by default, you need no ^
and $
anchors.