Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate username

I'm trying to create a regular expression to validate usernames against these criteria:

  1. Only contains alphanumeric characters, underscore and dot.
  2. Underscore and dot can't be at the end or start of a username (e.g _username / username_ / .username / username.).
  3. Underscore and dot can't be next to each other (e.g user_.name).
  4. Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
  5. Number of characters must be between 8 to 20.

This is what I've done so far; it sounds it enforces all criteria rules but the 5th rule. I don't know how to add the 5th rule to this:

 ^[a-zA-Z0-9]+([._]?[a-zA-Z0-9]+)*$ 
like image 213
mohsen dorparasti Avatar asked Aug 18 '12 11:08

mohsen dorparasti


People also ask

How do you validate a regular expression?

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

How do you validate a regular expression in Java?

This article shows how to use regex to validate a username in Java. Username consists of alphanumeric characters (a-zA-Z0-9), lowercase, or uppercase. Username allowed of the dot (.), underscore (_), and hyphen (-). The dot (.), underscore (_), or hyphen (-) must not be the first or last character.


2 Answers

^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$  └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘        │         │         │            │           no _ or . at the end        │         │         │            │        │         │         │            allowed characters        │         │         │        │         │         no __ or _. or ._ or .. inside        │         │        │         no _ or . at the beginning        │        username is 8-20 characters long 

If your browser raises an error due to lack of negative look-behind support, use the following alternative pattern:

^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$ 
like image 151
Ωmega Avatar answered Oct 07 '22 14:10

Ωmega


As much as I love regular expressions I think there is a limit to what is readable

So I would suggest

new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) && !username.StartsWith(".") && !username.StartsWith("_") && !username.EndsWith(".") && !username.EndsWith("_") && !username.Contains("..") && !username.Contains("__") && !username.Contains("._") && !username.Contains("_."); 

It's longer but it won't need the maintainer to open expresso to understand.

Sure you can comment a long regex but then who ever reads it has to rely on trust.......

like image 45
James Kyburz Avatar answered Oct 07 '22 14:10

James Kyburz