用戶輸入密碼時,實時檢測並顯示三條規則的滿足狀態:
<input type="password" id="pwd" placeholder="請輸入密碼" />
<div id="rule1">包含大小寫字母</div>
<div id="rule2">包含至少一個數字或特殊符號</div>
<div id="rule3">長度至少 8 位</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
function checkPasswordStrength() {
var val = this.value;
// 規則 1:大小寫字母
var hasLower = /[a-z]/.test(val);
var hasUpper = /[A-Z]/.test(val);
$('#rule1').css('color', hasLower && hasUpper ? 'green' : '#999');
// 規則 2:數字或特殊符號
var hasDigitOrSpecial = /[\d~!@#$%^&*()_]/.test(val);
$('#rule2').css('color', hasDigitOrSpecial ? 'green' : '#999');
// 規則 3:長度
$('#rule3').css('color', val.length >= 8 ? 'green' : '#999');
}
// 綁定事件:input (現代瀏覽器) + propertychange (IE 兼容)
$('#pwd').on('input propertychange', checkPasswordStrength);
</script>
/[a-z]/、/[A-Z]/、/[\d\W]/(非單字字符含符號)精準匹配字符類別。input 事件覆蓋輸入法、粘貼、拖拽等所有值變化場景;propertychange 兼容舊版 IE。.css('color', condition ? 'green' : '#999') 根據布爾值即時更新顏色。requestAnimationFrame 節流。// 綜合強度評分(0-4)
function getStrengthScore(val) {
var score = 0;
if (val.length >= 8) score++;
if (/[a-z]/.test(val) && /[A-Z]/.test(val)) score++;
if (/\d/.test(val)) score++;
if (/[\W_]/.test(val)) score++; // 特殊符號
return score;
}
// 顯示強度條
$('#pwd').on('input', function() {
var score = getStrengthScore(this.value);
var colors = ['#ddd', '#f00', '#fa0', '#ff0', '#0f0'];
$('#strength-bar').css({width: (score*25)+'%', background: colors[score]});
$('#strength-text').text(['極弱','弱','中等','強','極強'][score]);
});
const pwd = document.getElementById('pwd');
const rules = [
{el: document.getElementById('rule1'), test: v => /[a-z]/.test(v) && /[A-Z]/.test(v)},
{el: document.getElementById('rule2'), test: v => /[\d\W]/.test(v)},
{el: document.getElementById('rule3'), test: v => v.length >= 8}
];
pwd.addEventListener('input', () => {
const val = pwd.value;
rules.forEach(r => r.el.style.color = r.test(val) ? 'green' : '#999');
});
通過 input 事件 + 正則測試 + 動態樣式,即可實現流暢的密碼強度實時驗證反饋。