
註冊頁面的「密碼強度提示」是很典型的即時回饋互動。做法並不複雜:用 keyup 監聽輸入,再用幾條正則判斷符合哪一級,最後換掉背景圖的 class 就好。
先寫好四個 class,各自對應不同的背景圖,之後只要切換 class 就能換圖:
.qiang { background: url(/images/pas4.JPG) no-repeat; width:150px; height:40px; float:left; }
.zhong { background: url(/images/pas3.JPG) no-repeat; width:150px; height:40px; float:left; }
.ruo { background: url(/images/pas2.JPG) no-repeat; width:150px; height:40px; float:left; }
.ruox { background: url(/images/pas1.JPG) no-repeat; width:150px; height:40px; float:left; }
.div1css { float:left; width:200px; }
判斷的順序很關鍵,必須從最嚴格往最寬鬆檢查:
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#pass').keyup(function () {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#div2').addClass('ruox'); // 不足六位,全灰
}
else if (strongRegex.test($(this).val())) {
$('#div2').removeClass('zhong');
$('#div2').addClass('qiang'); // 八位以上且四類齊備
}
else if (mediumRegex.test($(this).val())) {
$('#div2').removeClass('ruo');
$('#div2').addClass('zhong'); // 七位以上且含兩類
}
else {
$('#div2').removeClass('ruox');
$('#div2').addClass('ruo'); // 六位以下一律算弱
}
return true;
});
});
</script>
<body>
<div id="div1" class="div1css">
<input type="password" name="pass" id="pass" />
</div>
<div id="div2"><span id="passstrength"></span></div>
</body>
正則裡的 (?=...) 是「零寬斷言」,也就是向前預查,它只約束後面的字元必須滿足條件,本身不消耗字元,因此可以把多個條件串在一起寫。另外,若要顯示文字提示而不只是換圖,把註解掉的 $('#passstrength').html('強!') 那幾行放回來即可。
需要留意的是,前端的強度檢測只是使用者體驗,真正的防護仍必須在伺服器端重做一份驗證,因為任何前端檢查都可以被繞過。