js 检查密码强弱方法
HTML 代码:
<form action="" autocomplete="off"> <input type="password" name="" id="pawd" placeholder="密码"><img src="" alt=""><br> <p>数字字符字母区分密码强弱</p><span id="ruo" style="display:inline-block">弱</span><span id="zo" style="display:inline-block">中</span><span id="qiang" style="display:inline-block">强</span><br> </form>
CSS 代码:
body { margin:0; padding:0; font-size:16px; } form { margin:0 auto; width:305px; transition:all 1s ease-out 0s; } input { font-size:16px; height:25px; width:280px; margin-top:20px; color:#333; outline:none; border-radius:5px; border:1px solid #ccc; } input:focus { border:1px solid #09f; } p { display:inline-block; font-size:12px; color:#ccc; margin:0; margin-right:6px; } span { display:none; width:42px; font-size:12px; margin-left:2px; color:#ccc; background:#ccc; text-align:center; } span.ruo { background:#f00; color:#fff; opacity:0.5; } span.zo { background:rgb(255,224,0); opacity:1; color:#fff; } span.qiang { background:rgb(3,146,3); color:#fff; }
JS 代码:
var pawd = document.querySelector('#pawd'); var state = '弱'; //模拟密码强度判断 pawd.onkeyup = function() { var regStr = /[a-zA-Z]/; //所有字母 var regNum = /[0-9]/; //所有数字 var sup = /W/; //所有非字母数字 if (this.value.length >= 1) { ruo.style.display = "inline-block"; ruo.className = "ruo"; ruo.innerHTML = "弱"; zo.style.display = "inline-block"; zo.className = ""; qiang.style.display = "inline-block"; qiang.className = ""; state = "弱"; } var sn = this.value.length >= 1 && regStr.test(this.value) && regNum.test(this.value); var sp = this.value.length >= 1 && regStr.test(this.value) && sup.test(this.value); var np = this.value.length >= 1 && regNum.test(this.value) && sup.test(this.value); if (sn || sp || np) { ruo.className = "zo"; ruo.innerHTML = " "; zo.className = "zo"; zo.innerHTML = "中"; state = "中"; } if (this.value.length >= 1 && regStr.test(this.value) && regNum.test(this.value) && sup.test(this.value)) { ruo.className = "qiang"; ruo.innerHTML = " "; zo.className = "qiang"; zo.innerHTML = " "; qiang.className = "qiang"; qiang.innerHTML = "强"; state = "强"; } if (this.value.length < 1) { ruo.style.display = "inline-block"; ruo.className = ""; ruo.innerHTML = "弱"; zo.style.display = "inline-block"; zo.className = ""; qiang.style.display = "inline-block"; qiang.className = ""; } }