.NET. Validate Password Using Regular Expressions


Here is how to manually check if a password validates against specific business rules in .NET.

The business rules are defined in a dictionary containing a pairs of regular expressions and user-friendly error message.

var patterns = new Dictionary();
patterns.Add(@"[a-z]", "Must have at least one lowercase letter");          // lowercase
patterns.Add(@"[A-Z]", "Must have at least one uppercase letter");         // uppercase
patterns.Add(@"[0-9]", "Must have at least one number");                      // digit
patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\]]", "Must have at least one symbol"); // special symbol
foreach (var pattern in patterns)
{
    if (password != null && Regex.IsMatch(password, pattern.Key) == false)
    {
        var error = pattern.Value;
        TempData["ErrorMessage"] = error;
        TempData.PopulateFrom(Request.Form);
        return RedirectToAction("Register", "Auth", new { Area = "Guest" });
    }
}