Home > Software design >  Validation of a username in a function?
Validation of a username in a function?

Time:12-14

New to regex and I don't know how to get the following to work My username needs to be 4 characters long and not exceed 10. Also only letters and numbers and not contain a hyphen. Also not start with a letter and it cannot end with a hyphen.

I don't want to use all kinds of if statements but I'd like to use a nice regex. Can someone help me?

private bool ValidateUserName(string username)
{
//todo create my regex 
}

Thanks.

CodePudding user response:

^[a-zA-Z]\w{3,9}$ should work

  • ^ asserts position at start of a line
  • [a-zA-Z] first character is a letter
  • \w matches any word character (equivalent to [a-zA-Z0-9_]) {3,9} matches the previous token between 3 and 9 times, as many times as possible, giving back as needed (greedy) $ asserts position at the end of a line

Keep in mind that \w includes the _ character. if you don't want that use [a-zA-Z0-9] instead of \w

CodePudding user response:

Well, let's clarify the requirements, the initial are:

  1. Username needs to be 4 characters long and not exceed 10
  2. Also only letters and numbers and not contain a hyphen
  3. Also not start with a letter

The refined can be

  1. Starts from digit (see initial 2, 3)
  2. Followed by [3..9] (see initial 1) letters or digits (initial 2)

Pattern:

^\d[\d\p{L}]{3,9}$

Code:

private static bool ValidateUserName(string username) =>
  username != null && Regex.IsMatch(username, @"^\d[\d\p{L}]{3,9}$");
  • Related