萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 密碼強度即時檢測與視覺化提示

HTML 結構

<input type="password" id="pwd" placeholder="請輸入密碼" />
<div id="strengthBar"><div id="strengthFill"></div></div>
<span id="strengthText"></span>

CSS 樣式

#strengthBar { width: 200px; height: 6px; background: #eee; border-radius: 3px; overflow: hidden; }
#strengthFill { height: 100%; width: 0%; transition: width 0.3s, background 0.3s; }
.weak { background: #e74c3c; }
.medium { background: #f39c12; }
.strong { background: #2ecc71; }

JS 邏輯:四大檢測函式

function charTypeCount(str) {
    var types = 0;
    if (/[a-z]/.test(str)) types++;
    if (/[A-Z]/.test(str)) types++;
    if (/\d/.test(str)) types++;
    if (/[^A-Za-z0-9]/.test(str)) types++;
    return types;
}

function getStrengthLevel(pwd) {
    var len = pwd.length, types = charTypeCount(pwd);
    if (len < 6) return 0; // 極弱
    if (len < 8) return types >= 3 ? 2 : 1;
    if (len < 12) return types >= 3 ? 3 : 2;
    return types >= 4 ? 4 : 3;
}

function updateStrengthUI(pwd) {
    var level = getStrengthLevel(pwd);
    var $fill = $('#strengthFill'), $text = $('#strengthText');
    $fill.removeClass('weak medium strong');
    if (level <= 1) { $fill.addClass('weak').css('width', '25%'); $text.text('弱'); }
    else if (level === 2) { $fill.addClass('medium').css('width', '50%'); $text.text('中'); }
    else if (level === 3) { $fill.addClass('strong').css('width', '75%'); $text.text('強'); }
    else { $fill.addClass('strong').css('width', '100%'); $text.text('極強'); }
}

$('#pwd').on('input', function(){ updateStrengthUI(this.value); });

進階:zxcvbn 強度估算

推薦引用 zxcvbn,能識別常見密碼、鍵盤走勢、單詞組合,給出破解時間估算,比簡單規則更科學。

完整頁面

將上述 HTML、CSS、JS 合併為單一檔案即可直接測試。

copyright © 萬盛學電腦網 all rights reserved