首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 實現密碼強度實時驗證:正則匹配與動態樣式切換

     編輯:程式設計疑難解答

需求效果

用戶輸入密碼時,實時檢測並顯示三條規則的滿足狀態:

  • 包含大小寫字母 → 綠色/灰色
  • 包含數字或特殊符號 → 綠色/灰色
  • 長度 ≥ 8 位 → 綠色/灰色

完整實現代碼

<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>

核心技術點

  1. 正則表達式:/[a-z]/、/[A-Z]/、/[\d\W]/(非單字字符含符號)精準匹配字符類別。
  2. 事件選擇:input 事件覆蓋輸入法、粘貼、拖拽等所有值變化場景;propertychange 兼容舊版 IE。
  3. 樣式動態切換:.css('color', condition ? 'green' : '#999') 根據布爾值即時更新顏色。
  4. 性能:正則測試極快,無需防抖;若規則復雜可考慮 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]);
});

無 jQuery 原生實現


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 事件 + 正則測試 + 動態樣式,即可實現流暢的密碼強度實時驗證反饋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved