I\'m trying to create a regular expression to validate usernames against these criteria:
This one should do the trick:
if (Regex.IsMatch(text, @"
# Validate username with 5 constraints.
^ # Anchor to start of string.
# 1- only contains alphanumeric characters , underscore and dot.
# 2- underscore and dot can't be at the end or start of username,
# 3- underscore and dot can't come next to each other.
# 4- each time just one occurrence of underscore or dot is valid.
(?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
# 5- number of characters must be between 8 to 20.
[A-Za-z0-9_.]{8,20} # Apply constraint 5.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace))
{
// Successful match
} else {
// Match attempt failed
}