Thanks Nicholas Carey. I was going to use regex first but what you wrote changed my mind. It is so much easier to maintain this way.
//You can set these from your custom service methods
int minLen = 8;
int minDigit 2;
int minSpChar 2;
Boolean ErrorFlag = false;
//Check for password length
if (model.NewPassword.Length < minLen)
{
ErrorFlag = true;
ModelState.AddModelError("NewPassword", "Password must be at least " + minLen + " characters long.");
}
//Check for Digits and Special Characters
int digitCount = 0;
int splCharCount = 0;
foreach (char c in model.NewPassword)
{
if (char.IsDigit(c)) digitCount++;
if (Regex.IsMatch(c.ToString(), @"[!#$%&'()*+,-.:;<=>?@[\\\]{}^_`|~]")) splCharCount++;
}
if (digitCount < minDigit)
{
ErrorFlag = true;
ModelState.AddModelError("NewPassword", "Password must have at least " + minDigit + " digit(s).");
}
if (splCharCount < minSpChar)
{
ErrorFlag = true;
ModelState.AddModelError("NewPassword", "Password must have at least " + minSpChar + " special character(s).");
}
if (ErrorFlag)
return View(model);