Mark Allison
Mark Allison

Reputation: 7228

What's wrong with my regex to validate a pattern in my html input?

I have an input box on my site and I want to validate that it is between 4 and 30 characters that are alphanumeric or any of . _ - (dot, underscore, hyphen).

e.g. these are valid:

not valid:

In my html I have this line:

<input id="handletext" type="text" spellcheck="false" pattern="^[\w-\.]{4,30}$" maxlength="30" />

I get an error in the debugger when I load the page in latest Chrome:

Pattern attribute value ^[\w-.]{4,30}$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^[\w-.]{4,30}$/: Invalid character class.

Any ideas what's wrong with my pattern?

Upvotes: 1

Views: 2047

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626816

2023 Update*

Now, escape the hyphen inside character classes even at the end of it:

pattern="[\w.\-]{4,30}"

Original answer

You must escape the hyphen or put it at the start/end of the character class and you also need to remove escaping backslash from .. As . is not a special char inside a character class, it should not be escaped in a pattern that is compiled with u modifier (and it is compiled with that flag in most browsers, Chrome included).

Use

pattern="[\w.-]{4,30}"

Note that you do not need ^ and $, the anchors are added automatically by the HTML5 engine.

In Chorme, the pattern will be compiled as /^(?:[\w.-]{4,30})$/u regex and will match a string that consists of four to thirty ASCII letters, digits, _, . or - chars.

Upvotes: 7

cn0047
cn0047

Reputation: 17071

pattern="[\w\-\.]{4,30}" works for me, so you also may try it.
The point here is that you must escape the hyphen.

Upvotes: 1

Related Questions