Tristan
Tristan

Reputation: 1790

How to make this regex safari / iOS compliant?

I am using this regex to validate usernames for my app. 3-20 characters, alphanumeric, and underscores. Not beginning with, or ending with an underscore and not having two consecutive underscores.

username.search(/^(?=.{3,20}$)(?![_])(?!.*[_]{2})[a-zA-Z0-9_]+(?<![_])$/)

But is is failing on iOS / safari with this error:

SyntaxError: Invalid regular expression: invalid group specifier name

How can I make this regex work in all major browsers?

Upvotes: 0

Views: 7246

Answers (3)

The fourth bird
The fourth bird

Reputation: 163362

You could omit the negative lookbehind at the end, but also omit the other 2 negative lookaheads (?![_])(?!.*[_]{2}) and only use the one at the start to check for the length 3 - 20.

Instead of the 2 negative lookaheads, you could match 1+ times [a-zA-Z0-9] so that the string can not start with an underscore.

Then use a repeating pattern to match a single _ followed by again 1+ times [a-zA-Z0-9] so that the string can not end with an underscore.

^(?=.{3,20}$)[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)+$

See the Regex demo

Upvotes: 2

Emma
Emma

Reputation: 27723

I'm guessing that you could simplify and try for instance with an expression similar to:

^(?![_])(?!.*[_]{2})[a-zA-Z0-9_]{2,19}[a-zA-Z0-9]$

Upvotes: 0

Trevor Reimer
Trevor Reimer

Reputation: 36

From my past experience using negative look behind in Javascript is not well supported.

You can see must browsers do not support it in the can I use website. The Regex Pal website also shows an error for this and recommends not to use it.

ps. I didn't have time to create a regex that would work for you.

Upvotes: 0

Related Questions