js实现密码强度验证
1 <html> 2 <head> 3 <meta http-equiv="content-type" content="text/html"; charset="utf-8"/> 4 <script src="./js/jquery-1.8.0.min.js"></script> 5 <script type="text/javascript"> 6 //CharMode函数 7 //测试某个字符是属于哪一类. 8 function CharMode(iN){ 9 if (iN>=48 && iN <=57) //数字 10 return 1; 11 if (iN>=65 && iN <=90) //大写字母 12 return 2; 13 if (iN>=97 && iN <=122) //小写 14 return 4; 15 else 16 return 8; //特殊字符 17 } 18 19 //bitTotal函数 20 //计算出当前密码当中一共有多少种模式 21 function bitTotal(num){ 22 modes=0; 23 for (i=0;i<4;i++){ 24 if (num & 1) modes++; 25 num>>>=1; 26 } 27 return modes; 28 } 29 30 //checkStrong函数 31 //返回密码的强度级别 32 33 function checkStrong(sPW){ 34 if (sPW.length<=4) 35 return 0; //密码太短 36 Modes=0; 37 for (i=0;i<sPW.length;i++){ 38 //测试每一个字符的类别并统计一共有多少种模式. 39 Modes|=CharMode(sPW.charCodeAt(i)); 40 } 41 42 return bitTotal(Modes); 43 44 } 45 46 //pwStrength函数 47 //当用户放开键盘或密码输入框失去焦点时,根据不同的级别显示不同的颜色 48 49 function pwStrength(pwd){ 50 O_color="#eeeeee"; 51 L_color="#FF0000"; 52 M_color="#FF9900"; 53 H_color="#33CC00"; 54 if (pwd==null||pwd==''){ 55 Lcolor=Mcolor=Hcolor=O_color; 56 } 57 else{ 58 S_level=checkStrong(pwd); 59 switch(S_level) { 60 case 0: 61 Lcolor=Mcolor=Hcolor=O_color; 62 case 1: 63 Lcolor=L_color; 64 Mcolor=Hcolor=O_color; 65 break; 66 case 2: 67 Lcolor=Mcolor=M_color; 68 Hcolor=O_color; 69 break; 70 default: 71 Lcolor=Mcolor=Hcolor=H_color; 72 } 73 } 74 75 document.getElementById("strength_L").style.background=Lcolor; 76 document.getElementById("strength_M").style.background=Mcolor; 77 document.getElementById("strength_H").style.background=Hcolor; 78 return; 79 } 80 </script> 81 </head> 82 <body> 83 <div> 84 <form name="form1" action="" > 85 输入密码:<input type="password" size="15" onKeyUp="pwStrength(this.value)" onBlur="pwStrength(this.value)"> 86 <br/>密码强度: 87 <table width="217" border="1" cellspacing="0" cellpadding="1" bordercolor="#cccccc" height="23" style='display:inline'> 88 <tr align="center" bgcolor="#eeeeee"> 89 90 <td width="33%" id="strength_L">弱</td> 91 <td width="33%" id="strength_M">中</td> 92 <td width="33%" id="strength_H">强</td> 93 </tr> 94 </table> 95 96 </form> 97 </div> 98 </body> 99 </html>
不定期会发布一些实用的Java开发文章