Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need regular expression to validate username

Tags:

regex

Need a regular expression to validate username which:

  1. should allow trailing spaces but not spaces in between characters
  2. must contain at least one letter,may contain letters and numbers
  3. 7-15 characters max(alphanumeric)
  4. cannot contain special characters
  5. underscore is allowed

Not sure how to do this. Any help is appreciated. Thank you.

This is what I was using but it allows space between characters

"(?=.*[a-zA-Z])[a-zA-Z0-9_]{1}[_a-zA-Z0-9\\s]{6,14}"

Example: user name No spaces are allowed in user name

like image 277
1078081 Avatar asked Oct 10 '22 08:10

1078081


1 Answers

Try this:

foundMatch = Regex.IsMatch(subjectString, @"^(?=.*[a-z])\w{7,15}\s*$", RegexOptions.IgnoreCase);

Is also allows the use of _ since you allowed this in your attempt.

So basically I use three rules. One to check if at least one letter exists. Another to check if the string consists only of alphas plus the _ and finally I accept trailing spaces and at least 7 with a max of 15 alpha's. You are in a good track. Keep it up and you will be answering questions here too :)

Breakdown:

    "
^           # Assert position at the beginning of the string
(?=         # Assert that the regex below can be matched, starting at this position (positive lookahead)
   .        # Match any single character that is not a line break character
      *     # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [a-z]    # Match a single character in the range between “a” and “z”
)
\w          # Match a single character that is a “word character” (letters, digits, etc.)
   {7,15}   # Between 7 and 15 times, as many times as possible, giving back as needed (greedy)
\s          # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *        # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$           # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
like image 55
FailedDev Avatar answered Oct 13 '22 10:10

FailedDev