开发者

.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 foll开发者_运维知识库owing specs:

It must be between 6 and 20 characters with at least one upper case letter, one lower case letter and one digit


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜