How to set RegEx global flag in HTML pattern attribute of the input element?

Viewed 779

I want to client validate a form input (username + password) before sending it to the server (php). Therefore I applied the pattern attribute in the input tag. I came up with a RegEx expression that does the job on the server side:

(preg_match_all('/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/', $_POST['username']) == 0)

thereby the global flag is set using preg_match_all (instead of preg_match).

Now I wanted to implement the same RegEx in my pattern attribute in the HTML form. HTML standard defines that RegEx in the pattern attribute follows RegEx in JavaScript, which devides the expression into "pattern, flags" divided by a comma. I would translate that into HTML like this:

pattern="^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$,g"

That doesn't work.

All JavaScript RegEx validators I have found enclose the pattern into slashes:

/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/

and say, that the global flag would be behind the last slash:

pattern="/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/g"

That doesn't work either.

Mozilla also states in their developer guide (I also read it elsewhere):

No forward slashes should be specified around the pattern text.

So, how can I get the global flag into the pattern attribute of the input element?

1 Answers

There are a couple of facts you should be aware when using pattern attribute regex:

  • There is no need to use g flag, the whole string must match the regex, and the regex check will only be performed once, a single match is enough
  • There is no need wrapping the pattern with regex delimiters, and if you add slashes at the start and end, they will be treated as literal slashes making part of the regex pattern, and in 99.9% of cases that would ruin the regex
  • You do not even need ^ and $ anchors as the pattern regex must match the entire string input. In fact, the pattern is automatically enclosed with ^(?: and )$, so if you use pattern="^\d+$" (just a quick example), the final regex (in Chrome, e.g.) will look like /^(?:^\d+$)$/u, which looks rather redundant.

So, all you need is

pattern="^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}"
// Or even
pattern="^[\w. äöüßÄÖÜ@-]{1,50}"

Note that [A-Za-z0-9_] = \w in JavaScript regex.

Related