前言
密码,如果设置的太简单,很容易就被攻破,所以很多网站将密码设置的要求设置的挺严格,一般是字母、数字、字符3选2,区分大小写。对于设置得太简单的密码,予以错误提示。或者予以密码等级(低中高)显示,让用户设置高级密码。那如何利用JS实现呢?
代码
链接:https://gist.github.com/xuanfeng/a44f20cb4569d5b4cd5e
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function passwordLevel(password) { var Modes = 0; for (i = 0; i < password.length; i++) { Modes |= CharMode(password.charCodeAt(i)); } return bitTotal(Modes);
//CharMode函数 function CharMode(iN) { if (iN >= 48 && iN <= 57)//数字 return 1; if (iN >= 65 && iN <= 90) //大写字母 return 2; if ((iN >= 97 && iN <= 122) || (iN >= 65 && iN <= 90)) //大小写 return 4; else return 8; //特殊字符 }
//bitTotal函数 function bitTotal(num) { modes = 0; for (i = 0; i < 4; i++) { if (num & 1) modes++; num >>>= 1; } return modes; } } |
使用
普通使用
使用语法:passwordLevel(string)
验证规则:数字、大写字母、小写字母、特殊字符
函数结果:返回密码中包含的规则数
运行例子:
1 2 | passwordLevel("123456") //返回1 passwordLevel("Abc'123456") //返回4 |
结合jquery.validate.js使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // 添加验证方法:至少包含两种规则 $.validator.addMethod("strongPsw", function(value, element) { if(passwordLevel(value) == 1){return false;} return true }, "格式不符合");
// 开始验证 $(".form").validate({ rules: { pwd: { required: true, //必填 minlength: 6, //最小长度 maxlength: 32, //最大长度 strongPsw: true, //密码强度 }, repwd: { required: true, minlength: 6, maxlength: 32, equalTo: "#pwd" //再次填写密码需一致 } }
}); |
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
if(form.pwd1.value.length < 6) {
alert("Error: Password must contain at least six characters!");
form.pwd1.focus();
return false;
}
if(form.pwd1.value == form.username.value) {
alert("Error: Password must be different from Username!");
form.pwd1.focus();
return false;
}
re = /[0-9]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one number (0-9)!");
form.pwd1.focus();
return false;
}
re = /[a-z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
form.pwd1.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.pwd1.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.pwd1.focus();
return false;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
form.pwd1.focus();
return false;
}
alert("You entered a valid password: " + form.pwd1.value);
return true;
}
</script>
最后欢迎大家访问我的个人网站:1024s