linus_hologram
linus_hologram

Reputation: 1705

validate username with regex in javascript

I am a newbie to regex and would like to create a regular expression to check usernames. These are the conditions:

  1. username must have between 4 and 20 characters
  2. username must not contain anything but letters a-z, digits 0-9 and special characters -._
  3. the special characters -._ must not be used successively in order to avoid confusion
  4. the username must not contain whitespaces

Examples

I've tried to create my own regex and only got to the point where I specify the allowed characters:

[a-z0-9.-_]{4,20}

Unfortunately, it still matches a string if there's a whitespace in between and it's possible to have two special chars .-_ successively:

matches although whitespace and two dots successively

If anybody would be able to provide me with help on this issue, I would be extremely grateful. Please keep in mind that I'm a newbie on regex and still learning it. Therefore, an explanation of your regex would be great.

Thanks in advance :)

Upvotes: 1

Views: 2991

Answers (1)

GOTO 0
GOTO 0

Reputation: 47662

Sometimes writing a regular expression can be almost as challenging as finding a user name. But here you were quite close to make it work. I can point out three reasons why your attempt fails.

First of all, we need to match all of the input string, not just a part of it, because we don't want to ignore things like white spaces and other characters that appear in the input. For that, one will typically use the anchors ^ (match start) and $ (match end) respectively.

Another point is that we need to prevent two special characters to appear next to each other. This is best done with a negative lookahead.

Finally, I can see that the tool you are using to test your regex is adding the flags gmi, which is not what we want. Particularly, the i flag says that the regex should be case insensitive, so it should match capital letters like small ones. Remove that flag.

The final regex looks like this:

/^([a-z0-9]|[-._](?![-._])){4,20}$/

There is nothing really cryptic here, except maybe for the group [-._](?![-._]) which means any of -._ not followed by any of -._.

Upvotes: 6

Related Questions