The regular expression that we are using is listed in
listing 3. The numbers are adjustable and come from the XML file.
Listing 3
(?=^.{12,25}$)(?=(?:.*?\d){2})(?=.*[a-z])(?=(?:.*?[A-
Z]){2})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){2})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$
Shown in listing 4 is the code to generate regular
expression dynamically. So, tomorrow if your client told you to increase the
required digit in the password policy, you don't have to search or create a new
regular expression. All you have to do is change the setting in the PasswordPolicy.xml file. You can verify the regular
expression here.
Listing 4
void btnSubmit_Click(object sender, EventArgs e)
{
PasswordSetting passwordSetting = Helper.GetPasswordSetting();
StringBuilder sbPasswordRegx = new StringBuilder(string.Empty);
//min and max
sbPasswordRegx.Append(@"(?=^.{" + passwordSetting.MinLength + "," +
passwordSetting.MaxLength + "}$)");
//numbers length
sbPasswordRegx.Append(@"(?=(?:.*?\d){" + passwordSetting.NumsLength + "})");
//a-z characters
sbPasswordRegx.Append(@"(?=.*[a-z])");
//A-Z length
sbPasswordRegx.Append(@"(?=(?:.*?[A-Z]){" + passwordSetting.UpperLength + "})");
//special characters length
sbPasswordRegx.Append(@"(?=(?:.*?[" + passwordSetting.SpecialChars + "]){" +
passwordSetting.SpecialLength + "})");
//(?!.*\s) - no spaces
//[0-9a-zA-Z!@#$%*()_+^&] -- valid characters
sbPasswordRegx.Append(@"(?!.*\s)[0-9a-zA-Z" + passwordSetting.SpecialChars +
"]*$");
if (Regex.IsMatch(txtPassword.Text, sbPasswordRegx.ToString()))
{
ResultLabel.Text = "Password confront password policy!";
}
else
{
ResultLabel.Text = "Password does not confront password policy!";
}
}