William
William

Reputation: 3405

Regular Expression for Username for ASP.NET

I am trying to create a regular expression to validate a username. I would like it to follow this rule:

Contains between 5 and 20 alphanumeric characters (either lower or upper case) and up to a single period (but not at the end or the beginning).

So far I have come up with the following:

(?:[a-zA-Z0-9]|([.])(?!\1)){5,20}$

This works in most cases, but it still allows usernames to have a period at the end and the beginning - could someone help me tweak it?

Upvotes: 0

Views: 1288

Answers (2)

rtf_leg
rtf_leg

Reputation: 1819

Try this one:

^(?i)(((?=.{6,21}$)[a-z\d]+\.[a-z\d]+)|[a-z\d]{5,20})$

This regex is:

  • (?i) - case insensitive (you can also achieve this with RegexOptions);
  • ((?=.{6,21}$)[a-z\d]+\.[a-z\d]+) - match 6-21 chars if string contain single period;
  • [a-z\d]{5,20} match 5-20 chars if string not contain period.

Upvotes: 4

Lorenz Meyer
Lorenz Meyer

Reputation: 19945

This would be an simple solution :

^[a-zA-Z0-9][.a-zA-Z0-9]{3,18}[a-zA-Z0-9]$

Just specify a character class without dot for the first and the last character.

Upvotes: 1

Related Questions