I need a regex to validate passwords with the following specs:
It must be between 6 and 20 characters with at least one upper case letter, one lower case letter and one digit
I need a regex to validate passwords with the following specs:
It must be between 6 and 20 characters with at least one upper case letter, one lower case letter and one digit
Regexes are used for searching, not for validation. You should not strive to do this in a single regex.
That being said, since you are looking for character classes, and since regexes support them very well, I would suggest using two or three regexes, checking for a match of each one.
bool IsPasswordValid(string password)
{
if (string.IsNullOrEmpty(password) ||
password.Length > 20 ||
password.Length < 6)
{
return false;
}
else if(!Regex.IsMatch(password, "\d") ||
!Regex.IsMatch(password, "[a-z]") ||
!Regex.IsMatch(password, "[A-Z]"))
{
return false;
}
else
{
return true;
}
}
This is WAY more efficient than trying to encode all of the possible combinations in an overly complicated Regex.
I think this works:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{6,20}$
Here it is with test cases in Regex Hero.
The idea is to use positive lookaheads to ensure that at least one lower case letter, one upper case letter, and one digit are contained within the password. And then as a last step I simply specify a dot to allow any characters in the 6-20 character range.