13

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.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Maurice Byrne
  • 153
  • 1
  • 1
  • 6

1 Answers1

19

You only need to escape the characters in the character class that must be escaped otherwise, you will always get this error.

Use

pattern="(?:\w:|\\)(\\[\w\s.()~!@#$%^&=+';,{}[\]-]+)+\.exe"

See the JSFiddle

Details:

  • The hyphen must be at the end of the character class
  • The ] inside the character class must be escaped
  • The [ and . must not be escaped
  • The : must never be esacaped, it is never a special character
  • [a-zA-Z0-9_] = \w
  • The pattern is always anchored by default, you need no ^ and $ anchors.
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
  • Invalid regular expression: /[\w'\,\.\(\)\-\\/\+\!]{1,}/: Invalid escape, I am getting this error for one of my form:input tags regex in pattern attribute, in JSP page. Any suggestions on this escaping of backslash \ ? – rinilnath Dec 08 '21 at 11:52
  • 1
    @rinilnath Of course. Why did you escape every char in the character class? *You only need to escape the characters in the character class that must be escaped*. So, something like `pattern="[\w\x27,.()/+!-]+"` will work. – Wiktor Stribiżew Dec 08 '21 at 11:52
  • so i can escape that \ without this?, i tried this in https://www.regextester.com/ it was escaping \, any easier way please – rinilnath Dec 08 '21 at 11:55
  • Stribizew, Thanks much, but one small doubt, is it ok to escape the "SPACE" character with backslash or i can just give the space somewhere in regex group – rinilnath Dec 08 '21 at 12:13
  • 1
    @rinilnath **You only need to escape the characters in the character class that must be escaped.** Is space a special regex metacharacter? No. So, DON'T. – Wiktor Stribiżew Dec 08 '21 at 12:19