下面的JS代码用于验证密码强度,最强的为100
<!DOCTYPE HTML> <html> <head> <title>Password Strength</title> </head> <script> function password_strength(string){ var h = 0; var size = string.length; var result = {}; string = ('' + string).split('').sort().join('').match(/(.)\1*/g); for (i = 0; i != string.length; i += 1) { result[string[i].charCodeAt(0)] = string[i].length; } for(var i in result){ var p = result[i] / size; h -= p * Math.log(p) / Math.log(2); } var strength = (h / 4) * 100; if(strength > 100){ strength = 100; } return strength; } </script> <body> <p> <input type="text" id="password" /> </p> <div style="position: absolute;width: 300px;border:solid 1px;height: 20px;background-color: red;"> <div style="position: absolute;width: 0;height: 20px;background-color: green;" id="green-bar"></div> <span id="str" style="position: absolute;width: 100%;left:0;right: 0;text-align: center;color: white;font-weight: bold;">0%</span> </div> <script> document.getElementById("password").onkeyup = function(){ var val = this.value; var strength = Math.round(password_strength(val)); document.getElementById("green-bar").style.width = strength + "%"; document.getElementById("str").innerText = strength + "%"; }; </script> </body> </html>