Julius A
Julius A

Reputation: 39632

.NET RegEx to validate password 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

Upvotes: 0

Views: 9966

Answers (3)

grant
grant

Reputation: 872

This allows spaces and special characters, but should follow your specs:

^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$

I use Expresso to help test my .Net regular expressions.

Upvotes: 0

John Gietzen
John Gietzen

Reputation: 49554

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.

Upvotes: 4

Steve Wortham
Steve Wortham

Reputation: 22240

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.

Upvotes: 7

Related Questions