密码强度,指一个密码对抗猜测或是暴力破解的有效程度。设置一个高强度的密码是非常重要的。
javascript核心代码
window.onload = function() {
var PasswordInput = document.getElementById('password');
PasswordInput.value = '';
var sp = document.getElementsByTagName('span');
PasswordInput.onkeyup = function() {
//强度状态设为默认
sp[0].className = sp[1].className = sp[2].className = "default";
var pwd = this.value;
var result = 0;
for(var i = 0, len = pwd.length; i < len; ++i) {
result |= charType(pwd.charCodeAt(i));
//返回pwd第i位的Unicode编码
}
var PasswordLevel = 0;
//对result进行四次循环,计算其PasswordLevel
for(var i = 0; i <= 4; i++) {
if(result & 1) {
PasswordLevel++;
}
//右移一位
result = result >>> 1;
}
if(pwd.length >= 6) {
//当输入的密码大于6位,进行判断,switch判断密码强度并展示
switch(PasswordLevel) {
case 1:
sp[0].className = "weak";
break;
case 2:
sp[0].className = "medium";
sp[1].className = "medium";
break;
case 3:
case 4:
sp[0].className = "strong";
sp[1].className = "strong";
sp[2].className = "strong";
break;
}
}
}
}
function charType(num) {
//函数返回值返回在强度检测switch里面
if(num >= 48 && num <= 57) {
return 1;
}
if(num >= 97 && num <= 122) {
return 2;
}
if(num >= 65 && num <= 90) {
return 4;
}
return 8;
}
html:
效果图: