1

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:

  • hello-
  • goodbye23_.sd

not valid:

  • boo
  • nospecials%
  • this has a space

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?

2
  • @Ehssan that's what I have. Commented Dec 22, 2018 at 22:37
  • 1
    You must escape the hyphen or put it at the start/end of the character class and remove escaping backslash from .: pattern="[\w.-]{4,30}". You do not need ^ and $, the anchors are added automatically by the HTML5 engine. Commented Dec 22, 2018 at 22:41

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

7 Comments

How is the underscore matched?
Underscore is part of \w (I don't know why, but it is)
regarding the "2023 update" -- is there a reference to when the dash at the end of a character class started to require an escape? this didn't used to be necessary.
@MarkusUnterwaditzer I tried to go through all my "HTML5" tagged answers and add that information, but I would need much more time :) Here is the answer.
@NathanChappell Because the information is a bit outdated in this thread. See the comment right above yours, there is a link to the answer that is for you.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.