Sagar Deshpande Sagar Deshpande - 2 months ago 17
C# Question

Password criterion using regex.Current code is not wotking

I have a password criterion as:

Minimum password length is 8 characters. Password must contain characters from at least 3 of the following 4 categories:


  1. English upper case characters (A through Z)

  2. English lower case characters (a through z)

  3. Numerical digits (0 through 9)

  4. Non alpha-numerical characters (i.e. punctuation such as @#$%^+ ( )



I am using

Regex compareRegex = new Regex(@"^(?=.*[a-z]{1})(?=.*[A-Z]{1}).{7,}$");
Regex numRegex = new Regex(@"[a-zA-Z0-9].{7,}" );

if (compareRegex.IsMatch(strPassword))
{
int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
if (count >= 0)
return true;
if (numRegex.IsMatch(strPassword))
return true;
else
return false;
}
else if (numRegex.IsMatch(strPassword))
{
bool valid = false;
int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
valid = (count >= 0);
return valid;
}
else
{
return false
}


But it is not working. Pls help

Answer

Personally I'd just split that up into separate checks for each criteria

private static char[] controlCharacters = 
{ 
     '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', 
     '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
};

public static bool ValidPassword(string password)
{
    if (password.Length < 8)
        return false;
    int sets = 0;
    if (Regex.IsMatch(password, "[A-Z]"))
        sets++;
    if (Regex.IsMatch(password, "[a-z]"))
        sets++;
    if (Regex.IsMatch(password, "[0-9]"))
        sets++;
    if (password.IndexOfAny(controlCharacters)>=0)
        sets++;
    return sets > 2;
} 

Or if you want an optimized version that doesn't use regular expressions you can do this.

public static bool ValidPassword(string password)
{
    if (password.Length < 8)
        return false;
    bool[] sets = new bool[4];
    foreach (char c in password)
    {
        if(c >= 'A' && c <= 'Z')
            sets[0] = true;
        else if (c >= 'a' && c <= 'z')
            sets[1] = true;
        else if (c >= '0' && c <= '9')
            sets[2] = true;
        else if (controlCharacters.Contains(c))
            sets[3] = true;

        if (sets.Where(b=>b).Count() > 2)
            return true;
    }

    return false;
}

This one just loops through the characters and keeps track of each type it sees and once it's seen 3 or more of each type it returns true.

Comments