密碼輸入強度提示例項程式碼

antzone發表於2017-03-12

很多網站的登錄檔單,在填寫密碼的時候能夠實時的給出密碼強度提示,這可以提醒使用者當前輸入的密碼安全程度。

算是非常人性化的一個舉措,下面就通過一個例項簡單介紹一下如何實現此效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>密碼強度提示功能-螞蟻部落</title>
<script type="text/javascript"> 
function CharMode(iN) {
  if (iN >= 48 && iN <= 57) {
    return 1;
  }
  if (iN >= 65 && iN <= 90) {
    return 2;
  }
  if (iN >= 97 && iN <= 122) {
    return 4;
  } else {
    return 8;
  }
}
 
function bitTotal(num) {
  modes = 0;
  for (i = 0; i < 4; i++) {
    if (num & 1) modes++;
    num >>>= 1;
  }
  return modes;
}
 
function checkStrong(sPW) {
  if (sPW.length <= 4) {
    return 0;
  }
  Modes = 0;
  for (i = 0; i < sPW.length; i++) {
    Modes |= CharMode(sPW.charCodeAt(i));
  }
  return bitTotal(Modes);
}
 
function pwStrength(pwd) {
  O_color = "#eeeeee";
  L_color = "#FF0000";
  M_color = "#FF9900";
  H_color = "#33CC00";
  if (pwd == null || pwd == '') {
    Lcolor = Mcolor = Hcolor = O_color;
  } else {
    S_level = checkStrong(pwd);
    switch (S_level) {
      case 0:
        Lcolor = Mcolor = Hcolor = O_color;
      case 1:
        Lcolor = L_color;
        Mcolor = Hcolor = O_color;
        break;
      case 2:
        Lcolor = Mcolor = M_color;
        Hcolor = O_color;
        break;
      default:
        Lcolor = Mcolor = Hcolor = H_color;
    }
  }
  document.getElementById("strength_L").style.background = Lcolor;
  document.getElementById("strength_M").style.background = Mcolor;
  document.getElementById("strength_H").style.background = Hcolor;
  return;
}
window.onload = function() {
  var pw = document.getElementById("pw");
  pw.onkeyup = function() {
    pwStrength(this.value)
  }
  pw.onBlur = function() {
    pwStrength(this.value)
  }
}
</script> 
</head> 
<body> 
<table width="250" cellpadding="2"> 
  <tr> 
     <td width="40%" align="right">密碼:</td> 
     <td colspan="3" align="left"> 
      <input type="password" size="20" id="pw" /> 
     </td> 
  </tr> 
  <tr align="center"> 
    <td width="40%" align="right">密碼強度:</td> 
    <td width="20%" id="strength_L" bgcolor="#f5f5f5">弱</td> 
    <td width="20%" id="strength_M" bgcolor="#f5f5f5">中</td> 
    <td width="20%" id="strength_H" bgcolor="#f5f5f5">強</td> 
  </tr> 
</table> 
</body> 
</html>

當輸入密碼的時候,能夠以顏色的形式實時提醒輸入密碼的強度。

相關文章