我使用此article解释了如何使用密码强度验证器。
问题是在输入密码时似乎没有检查和计算每一步。它似乎只检查超过6个字符,超过10个字符,最多可以计算3个字数。
问题可能是因为我正在使用TextChanged函数吗?
以下是验证码的代码:
enum PasswordScore
{
Blank = 0,
VeryWeak = 1,
Weak = 2,
Medium = 3,
Strong = 4,
VeryStrong = 5
}
private static PasswordScore CheckStrength(string password)
{
int score = 1;
if (password.Length < 1)
return PasswordScore.Blank;
if (password.Length < 4)
return PasswordScore.VeryWeak;
if (password.Length >= 6)
score++;
if (password.Length >= 10)
score++;
if (Regex.IsMatch(password, @"/\d+/", RegexOptions.ECMAScript))
score++;
if (Regex.IsMatch(password, @"/[a-z]/", RegexOptions.ECMAScript) &&
Regex.IsMatch(password, @"/[A-Z]/", RegexOptions.ECMAScript))
score++;
if (Regex.IsMatch(password, @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/",
RegexOptions.ECMAScript))
score++;
return (PasswordScore)score;
}
这是我的TextChanged函数(注意:我将值传递给检查方法的代码位于此代码的第二行):
// Checking user input for variety of things.
// This is intended as security measure.
private void validateInput(object sender, EventArgs e)
{
// ======== Start validating Password field ========
// Checking for Null or Empty string in password field.
if (string.IsNullOrEmpty(txtPassword.Text))
{
lblMessagePass.Text = "Password field cannot be empty!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Making sure that user name is at least 6 characters long.
else if (txtPassword.Text.Length < 6)
{
lblMessagePass.Text = "Password field must be at least 6 characters long!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Checking for password made of same repeating character.
// Invalid input example: 'aaaaaa'
else if (!txtPassword.Text.Distinct().Skip(1).Any())
{
lblMessagePass.Text = "Password cannot be made of repeating the same characters!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// Making sure that user name and password are not the same.
// Security measure.
else if (txtUserName.Text == txtPassword.Text)
{
lblMessagePass.Text = "User Name and Password can not be the same!";
lblMessagePass.ForeColor = Color.IndianRed;
btnAuthenticate.Enabled = false;
passIsValid = false;
}
// If all other checks aren't trigered; enable authentication.
else
{
lblMessagePass.Text = "Password is valid.";
lblMessagePass.ForeColor = Color.Green;
passIsValid = true;
if (passIsValid && userIsValid)
{
btnAuthenticate.Enabled = true;
}
}
// ======== End validating Password field ========
lblStrength.Text = CheckStrength(txtPassword.Text).ToString();
}
答案 0 :(得分:2)
您不需要正则表达式模式中的斜杠(/
)或最后一个中的逗号。
试试这个:
if (Regex.IsMatch(password, @"\d+", RegexOptions.ECMAScript))
score++;
if (Regex.IsMatch(password, @"[a-z]", RegexOptions.ECMAScript) &&
Regex.IsMatch(password, @"[A-Z]", RegexOptions.ECMAScript))
score++;
if (Regex.IsMatch(password, @".[!@#\$%\^&\*\?_~\-£\(\)]", RegexOptions.ECMAScript))
score++;