Validating password using regex c#

I recommend you create separate patterns to validate the password:

var input = "P@ssw0rd";

var hasNumber = new Regex(@"[0-9]+");
var hasUpperChar = new Regex(@"[A-Z]+");
var hasMinimum8Chars = new Regex(@".{8,}");

var isValidated = hasNumber.IsMatch(input) && hasUpperChar.IsMatch(input) && hasMinimum8Chars.IsMatch(input);
Console.WriteLine(isValidated);

there is problem with you regular expression

Regex regex = new Regex(@"^(.{0,7}|[^0-9]*|[^A-Z])$");

you applied character | which means either or.

form wiki

| -The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

which means that in your regular expression it either matches .{0,7} part or [^0-9]*|[^A-Z] - that is why its returning true to you in any case.


You can use this regex:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$

This regex will enforce these rules: • At least one upper case english letter • At least one lower case english letter • At least one digit • At least one special character • Minimum 8 in length

refered from : Regex for Password Must be contain at least 8 characters, least 1 number and both lower and uppercase letters and special characters


I have created a simple method to validate all kind of password. You can edit your limit on that. Kindly find the code given below.

private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,15}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 12 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}

Tags:

C#

Regex