JS实现验证输入框密码强度
JS实现验证输入框密码强度
<!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>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步