60. Validating passwords

You could solve this problem in several ways. For example, you could examine each character individually or you could use regular expressions. The approach I decided to take uses simple string methods. The following code uses those methods to validate passwords:

// See if the password satisfies the indicated criteria.
public static bool PasswordIsValid(this string password,
int minLength, int maxLength,
bool allowLowercase, bool requireLowercase,
bool allowUppercase, bool requireUppercase,
bool allowDigit, bool requireDigit,
bool allowSpecial, bool requireSpecial,
bool allowOther, bool requireOther, string other)
{
// See if the password has an allowed length.
if ((password.Length < minLength) || (password.Length > maxLength))
return false;

const string lowers = "abcdefghijklmnopqrstuvwxyz";
const string uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string digits = "0123456789";
const string specials = @"~!@#$%^&*():;[]{}<>,.?/|";

// Check requirements.
if (requireLowercase &&
(password.IndexOfAny(lowers.ToCharArray()) < 0))
return false;
if (requireUppercase &&
(password.IndexOfAny(uppers.ToCharArray()) < 0))
return false;
if (requireDigit &&
(password.IndexOfAny(digits.ToCharArray()) < 0))
return false;
if (requireSpecial &&
(password.IndexOfAny(specials.ToCharArray()) < 0))
return false;
if (requireOther &&
(password.IndexOfAny(other.ToCharArray()) < 0))
return false;

// Make a string containing all allowed characters.
string allowed = "";
if (allowLowercase) allowed += lowers;
if (allowUppercase) allowed += uppers;
if (allowDigit) allowed += digits;
if (allowSpecial) allowed += specials;
if (allowOther) allowed += other;

// Make sure all characters in the password are allowed.
password = password.Trim(allowed.ToCharArray());
if (password.Length > 0) return false;

return true;
}

The method first checks the password's length and returns false if the length is invalid.

Next, the code determines whether the password includes required characters. For example, if a lowercase letter is required, the code uses the IndexOfAny method to get the first index of any lowercase letter in the password. If there is no such character, the IndexOfAny method returns -1 and the code returns false to indicate that the password is invalid.

After checking for required characters, the method builds a string containing all of the allowed characters. It then uses the Trim method to remove those characters from the password. If the result is non-blank, then the password contains some characters that are not in the allowed string, so the method returns false.

Finally, if the password passes all of those checks, the method returns true to indicate that the password is valid.

Download the ValidatePasswords example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset