How to validate username in c# regular expression

We want to set the rules when user choosing their username. In most of cases, a pattern with letter and number is used. We also want to set the length of the username so it does not look ugly. We use the following regular expression to validate a username.

[a-zA-Z] => first character must be a letter
[a-zA-Z0-9] => it can contain letter and number
{5,11} => the length is between 6 to 12

public static bool IsUsername(string username)
{
      string pattern;
      // start with a letter, allow letter or number, length between 6 to 12.
      pattern = @"^[a-zA-Z][a-zA-Z0-9]{5,11}$";

      Regex regex = new Regex(pattern);
      return regex.IsMatch(username);
}
Advertisement