下面是使用JavaScript和C#编写的密码强度验证方法,要求密码长度至少为12位,并且必须包含大小写字母、数字、特殊符号中的任意三种。
JavaScript 实现
function validatePassword(password) {
const length = password.length >= 12;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumbers = /\d/.test(password);
const hasSpecialChars = /[^A-Za-z\d]/.test(password);
// Count how many conditions are met
const conditionsMet = [hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChars].filter(Boolean).length;
return length && conditionsMet >= 3;
}
// Example usage:
console.log(validatePassword('ExamplePass1!')); // true or false based on the criteriaC# 实现
using System;
using System.Text.RegularExpressions;
public class PasswordValidator
{
public static bool ValidatePassword(string password)
{
bool length = password.Length >= 12;
bool hasUpperCase = Regex.IsMatch(password, "[A-Z]");
bool hasLowerCase = Regex.IsMatch(password, "[a-z]");
bool hasNumbers = Regex.IsMatch(password, @"\d");
bool hasSpecialChars = Regex.IsMatch(password, @"[^A-Za-z\d]");
// Count how many conditions are met
int conditionsMet = (hasUpperCase ? 1 : 0) +
(hasLowerCase ? 1 : 0) +
(hasNumbers ? 1 : 0) +
(hasSpecialChars ? 1 : 0);
return length && conditionsMet >= 3;
}
public static void Main()
{
Console.WriteLine(ValidatePassword("ExamplePass1!")); // Outputs: True or False based on the criteria
}
}解释
长度检查:确保密码长度至少为12个字符。
字符类型检查:
大写字母:通过正则表达式
[A-Z]检查是否包含大写字母。小写字母:通过正则表达式
[a-z]检查是否包含小写字母。数字:通过正则表达式
\d检查是否包含数字。特殊字符:通过正则表达式
[^A-Za-z\d]检查是否包含非字母数字的字符(即特殊字符)。条件计数:统计满足的条件数量,确保至少满足三个条件。
这两种实现方式都可以有效地验证密码是否符合指定的复杂性要求。你可以根据需要调整正则表达式或添加更多的验证逻辑。
此文由通义AI生成。