Password Validation Method in C#
csharpC# and .NETvalidationregexsecurity
A ValidatePassword method that checks a password with regular expressions (upper and lower case letters, digits, symbols, 8 to 15 characters) and returns the reason it was rejected. The reqUpperCaseLetter, reqLowerCaseLetter, reqDecimalDigit and reqSpecialChar flags at the top choose which rules apply.
// needs: using System; using System.Text.RegularExpressions;
public static bool ValidatePassword(string password, out string ErrorMessage)
{
bool reqUpperCaseLetter = true;
bool reqLowerCaseLetter = false;
bool reqDecimalDigit = false;
bool reqSpecialChar = false;
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) && reqLowerCaseLetter ==true)
{
ErrorMessage = "Password should contain at least one lower case letter.";
return false;
}
else if (!hasUpperChar.IsMatch(input) && reqUpperCaseLetter ==true)
{
ErrorMessage = "Password should contain at least one upper case letter.";
return false;
}
else if (!hasMiniMaxChars.IsMatch(input))
{
ErrorMessage = "Password should not be lesser than 8 or greater than 15 characters.";
return false;
}
else if (!hasNumber.IsMatch(input) && reqDecimalDigit==false)
{
ErrorMessage = "Password should contain at least one numeric value.";
return false;
}
else if (!hasSymbols.IsMatch(input) && reqSpecialChar ==false)
{
ErrorMessage = "Password should contain at least one special case character.";
return false;
}
else
{
ErrorMessage = "Success";
return true;
}
}
Comments
Loading comments…