標籤:
JavaScript的方法:
1 <script type="text/javascript"> 2 window.onload = function () { 3 document.getElementById(‘txt‘).onkeydown = function () { 4 5 //擷取td 6 var tds = document.getElementById(‘tb‘).getElementsByTagName(‘td‘); 7 for (var i = 0; i < tds.length; i++) { 8 tds[i].style.backgroundColor = ‘#E6E6E6‘; 9 }10 11 var pwd = this.value; //擷取密碼12 if (pwd.length > 0) {13 var result = getPassWord(pwd);14 if (result <= 1) {15 //弱16 tds[0].style.backgroundColor = ‘red‘;17 } else if (result == 2) {18 //中19 tds[0].style.backgroundColor = ‘orange‘;20 tds[1].style.backgroundColor = ‘orange‘;21 } else if (result == 3) {22 //強23 tds[0].style.backgroundColor = ‘green‘;24 tds[1].style.backgroundColor = ‘green‘;25 tds[2].style.backgroundColor = ‘green‘;26 }27 28 }29 }30 }31 //利用Regex匹配相關字串,返回密碼的強度值32 function getPassWord(pwdMsg) {33 var lvl = 0;34 /*35 var reg = /\d/;36 if (reg.test(pwdMsg)) {37 lvl++;38 };39 */40 //密碼中有數字加141 if (pwdMsg.match(/\d/)) {42 lvl++;43 }44 //密碼中有字元加145 if (pwdMsg.match(/[a-zA-Z]/)) {46 lvl++;47 }48 //密碼中有其他字元加149 if (pwdMsg.match(/^[0-9a-zA-Z]/)) {50 lvl++;51 }52 //密碼小於6位減一53 if (pwdMsg.length <= 6) {54 lvl--;55 }56 return lvl;57 }58 </script>
頁面內容:
1 <input type="text" id="txt" name="name" value="" /> 2 <table border="1" cellpadding="0" cellspacing="0" id="tb"> 3 <tr> 4 <td> 5 弱 6 </td> 7 <td> 8 中 9 </td>10 <td>11 強12 </td>13 </tr>14 </table>
簡單的樣式:
1 <style type="text/css">2 td3 {4 width: 100px;5 height: 25px;6 background-color: #E6E6E6;7 text-align: center;8 }9 </style>
JavaScript驗證密碼強度