第一种:
HTML部分:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>密码强度</title>
<style type="text/css">
#passStrength{height:6px;width:120px;border:1px solid #ccc;padding:2px;}
.strengthLv1{background:red;height:6px;width:40px;}
.strengthLv2{background:orange;height:6px;width:80px;}
.strengthLv3{background:green;height:6px;width:120px;}
</style>
</head>
<body>
<input type="password" name="pass" id="pass" maxlength="16"/>
<div class="pass-wrap">
<em>密码强度:</em>
<div id="passStrength"></div>
</div>
</body>
</html>
<script type="text/javascript" src="js/passwordStrength.js"></script>
<script type="text/javascript">
new PasswordStrength('pass','passStrength');
</script>
JavaScript部分:
function PasswordStrength(passwordID,strengthID){
this.init(strengthID);
var _this = this;
document.getElementById(passwordID).onkeyup = function(){
_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;}
if(lv > 3){lv=3;}
this.oStrength.className = 'strengthLv' + lv;
this.oStrengthTxt.innerHTML = aLvTxt[lv];
};
第二种:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证密码强度</title>
<style type="text/css">
*{margin: 0;padding: 0;}
body{background:#ccc;}
#demo{width:400px;padding:50px;background:#efefef;border: 1px solid #999;line-height:40px;margin:100px auto 0;}
#strength_length{height:6px;width:100px;padding:2px;border: 1px solid #ccc;}
.lv1{background:red;}
.lv2{background:blue;width:200px;}
.lv3{background:green;width:300px;}
</style>
</head>
<body>
<div id="demo">
<label for="ipt">密码:</label>
<input type="text" id="ipt"><br/>
<em>密码强度:</em><em id="strength"></em>
<div id="strength_length"></div>
</div>
</body>
<script type="text/javascript">
(function(window){
function $(id){
return document.getElementById(id);
};
var arr = ["","低","中","高"];
// 获取对象
var ipt = $("ipt"),strength = $("strength"),strLength = $("strength_length");
// 密码输入事件
ipt.onkeyup = function(){
var s = 0;
var txt = this.value;
if( /[a-zA-Z]/.test(txt) ){
s++;
};
if( /[0-9]/.test(txt) ){
s++;
};
if( /[^0-9a-zA-Z]/.test(txt) ){
s++;
};
if( txt.length <6 ){
s = 0;
};
strength.innerHTML = arr[s];
strLength.className = "lv" + s;
}
})(window)
</script>
</html>