您的位置:首页 > Web前端 > JavaScript

JS验证密码强度

2018-02-01 21:33 471 查看
        验证“密码强度”的例子很常见,我们注册新的账号的时候往往设置密码,此时就遇到验证密码强度的问题了。“密码强度”也就是密码难易程度的意思。

        原理:

1、如果输入的密码为单纯的数字或者字母:提示“低”

2、如果是数字和字母混合的:提示“中” 

3、如果数字、字母、特殊字符都有:提示“强”

       下面是一种“密码强度”的验证方法,觉得很有意思。

HTML和CSS代码:

<!DOCTYPE HTML>
<html > <!-- lang="en" -->
<head>
<meta charset="utf-8" />
<title>密码强度</title>
<style type="text/css">

#pwdStrength {
height: 30px;
width: 180px;
border: 1px solid #ccc;
padding: 2px;

}
.strengthLv1 {
background: red;
height: 30px;
width: 60px;
}

.strengthLv2 {
background: orange;
height: 30px;
width: 120px;
}

.strengthLv3 {
background: green;
height: 30px;
width: 180px;
}
#pwd {
height:30px;
font-size :20px;
}
strong {
margin-left:90px;
}
#pwd1 {
color:red;
margin-top:5px;
margin-bottom:5px;
}
</style>
</head>
<body>
<input type="password" name="pwd" id="pwd" maxlength="16" />
<div class="pass-wrap">
<!--<em>密码强度:</em>-->
<p id="pwd1" name="pwd">密码强度:</p>
<div id="pwdStrength"></div>
</div>
</body>
</html>

javascript代码:

<script type="text/javascript">
function PasswordStrength(passwordID, strengthID) {
this.init(strengthID);
var _this = this;
document.getElementById(passwordID).onkeyup = function () {//onkeyup 事件,在键盘按键被松开时发生,进行判断
_this.checkStrength(this.value);
}
};
PasswordStrength.prototype.init = function (strengthID) {
var id = document.getElementById(strengthID);
var div = document.createElement('div');
var strong = document.createElement('strong');
this.oStrength = id.appendChild(div);
this.oStrengthTxt = id.parentNode.appendChild(strong);
};
PasswordStrength.prototype.checkStrength = function (val) { //验证密码强度的函数
var aLvTxt = ['', '低', '中', '高'];//定义提示消息的种类
var lv = 0; //初始化提示消息为空
if (val.match(/[a-z]/g)) { lv++; } //验证是否包含字母
if (val.match(/[0-9]/g)) { lv++; }  // 验证是否包含数字
if (val.match(/(.[^a-z0-9])/g)) { lv++; } //验证是否包含字母,数字,字符
if (val.length < 6) { lv = 0; } //如果密码长度小于6位,提示消息为空
if (lv > 3) { lv = 3; }
this.oStrength.className = 'strengthLv' + lv;
this.oStrengthTxt.innerHTML = aLvTxt[lv];
};
new PasswordStrength('pwd','pwdStrength');
</script>


效果图:







小结:1.利用onkeyup 事件(在键盘按键被松开时发生)进行三种判断,简单方便。2. 正则表达式的功能真的很强大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息