輸入密碼即時顯示強度等級:弱 / 中 / 強 / 非常好,配合顏色變化提升用戶體驗。
/**
* 密碼強度檢測
* @param {string} sValue - 密碼字串
* @returns {number} 1=弱 2=中 3=強 4=非常好 0=不合格
*/
function checkStrong(sValue) {
var modes = 0; // 字符類型計數
// 長度不足 6 直接判弱
if (sValue.length < 6) return modes;
// 四類字符檢測
if (/\d/.test(sValue)) modes++; // 數字
if (/[a-z]/.test(sValue)) modes++; // 小寫字母
if (/[A-Z]/.test(sValue)) modes++; // 大寫字母
if (/\W/.test(sValue)) modes++; // 特殊字符(非單字字符)
// 強度分級規則
switch (modes) {
case 1: return 1; // 單一類型 → 弱
case 2: return 2; // 兩類混合 → 中
case 3:
case 4: return sValue.length < 12 ? 3 : 4; // 三/四類:<12位=強,≥12位=非常好
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>密碼強度檢測</title>
<style>
body {font: 14px/1.5 Arial; padding: 20px;}
input {width: 250px; padding: 8px; font-size: 14px; border: 1px solid #ccc;}
input.correct {border-color: green;}
input.error {border-color: red;}
#tips {margin-top: 8px;}
#tips span {display: inline-block; width: 60px; height: 22px;
background: #ccc; color: #fff; text-align: center;
line-height: 22px; margin-right: 4px; overflow: hidden;}
#tips.s1 .active {background: #f30;} /* 弱 - 紅 */
#tips.s2 .active {background: #fc0;} /* 中 - 橙 */
#tips.s3 .active {background: #cc0;} /* 強 - 黃 */
#tips.s4 .active {background: #090;} /* 非常好 - 綠 */
</style>
</head>
<body>
<input type="password" id="pwd" maxlength="16" placeholder="請輸入密碼">
<div id="tips">
<span></span><span></span><span></span><span></span>
</div>
<script>
window.onload = function() {
var oTips = document.getElementById("tips");
var oInput = document.getElementById("pwd");
var aSpan = oTips.getElementsByTagName("span");
var aStr = ["弱", "中", "強", "非常好"];
oInput.onkeyup = oInput.onfocus = oInput.onblur = function() {
var index = checkStrong(this.value);
this.className = index ? "correct" : "error";
oTips.className = "s" + index;
for (var i = 0; i < aSpan.length; i++) {
aSpan[i].className = aSpan[i].innerHTML = "";
}
index && (aSpan[index-1].className = "active",
aSpan[index-1].innerHTML = aStr[index-1]);
};
};
</script>
</body>
</html>
| 字符類型數 | 長度 | 等級 | 顏色 |
|---|---|---|---|
| 1 類 | 任意 | 弱 | 紅 |
| 1 類 | < 6 | 弱 | 紅 |
| 2 類 | 任意 | 中 | 橙 |
| 3-4 類 | < 12 | 強 | 黃 |
| 3-4 類 | ≥ 12 | 非常好 | 綠 |
此實現輕量、無依賴,可直接整合至註冊/修改密碼頁面。