需求規格
- 長度:6-20 字元
- 必含:數字、字母 (大小寫)、特殊符號
- 禁用:中文等非 ASCII 字元 (字碼 > 127)
- 限制:不使用正則、JS、AJAX、jQuery,純 C# 方法
實作代碼
public static class PasswordValidator
{
// 允許的特殊字元集合
private static readonly HashSet<char> SpecialChars = new HashSet<char>(
"~!@#$%^&*()_+|`-=\\{}:\"<>?[];',./".ToCharArray()
);
public static bool Validate(string password)
{
if (string.IsNullOrEmpty(password)) return false;
if (password.Length < 6 || password.Length > 20) return false;
bool hasDigit = false;
bool hasLetter = false;
bool hasSpecial = false;
foreach (char c in password)
{
if (c > 127) return false; // 非 ASCII (含中文)
if (char.IsDigit(c)) hasDigit = true;
else if (char.IsLetter(c)) hasLetter = true;
else if (SpecialChars.Contains(c)) hasSpecial = true;
else return false; // 其他不可列印/控制字元
}
return hasDigit && hasLetter && hasSpecial;
}
}
使用範例
[HttpPost]
public ActionResult ChangePassword(string newPassword)
{
if (!PasswordValidator.Validate(newPassword))
{
ModelState.AddModelError("", "密碼必須 6-20 位,包含數字、字母、特殊符號,不含中文");
return View();
}
// ... 更新密碼邏輯
return RedirectToAction("Success");
}
設計說明
- 使用
HashSet<char> 存儲特殊字元,Contains 查找 O(1),效能優於字串 IndexOf。
- 單次遍歷同時完成所有檢查,時間複雜度 O(n),n 為密碼長度 (max 20),極快。
char.IsDigit/IsLetter 自動處理 Unicode 分類,但配合 c > 127 直接排除非 ASCII,滿足「禁中文」需求。
- 若未來需調整特殊字元集合,只需修改靜態初始化字串。