用Javascript评估用户输入密码的强度(Knockout版)

时间:2021-05-18

我们来看看如果使用Knockout更简单的来实现密码强度的验证。
原有代码请查看:
复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///js/knockout-1.2.1.js"></script>
</head>
<body>
<script type="text/javascript">
var Page = Page || {};
Page.Utility = Page.Utility || {};
Page.Utility.Registration = Page.Utility.Registration || {};
//获取密码强度
Page.Utility.Registration.getPasswordLevel =function (password) {
if (password ==null|| password =='')
return0;
if (password.length <=4)
return0; //密码太短
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) //数字
return1;
if (iN >=65&& iN <=90) //大写字母
return2;
if (iN >=97&& iN <=122) //小写
return4;
else
return8; //特殊字符
}
//bitTotal函数
function bitTotal(num) {
modes =0;
for (i =0; i <4; i++) {
if (num &1) modes++;
num >>>=1;
}
return modes;
}
};
var viewModel = {
Password: ko.observable(""),
Ocolor: "#eeeeee"
};
viewModel.PasswordLevel = ko.dependentObservable(function () {
return Page.Utility.Registration.getPasswordLevel(this.Password());
}, viewModel);
viewModel.Lcolor = ko.dependentObservable(function () {
//根据密码强度判断第一个格显示的背景色
returnthis.PasswordLevel() ==0?this.Ocolor : (this.PasswordLevel() ==1?"#FF0000" : (this.PasswordLevel() ==2?"#FF9900" : "#33CC00"))
}, viewModel);
viewModel.Mcolor = ko.dependentObservable(function () {
//根据密码强度判断第二个格显示的背景色
returnthis.PasswordLevel() <2?this.Ocolor : (this.PasswordLevel() ==2?"#FF9900" : "#33CC00")
}, viewModel);
viewModel.Hcolor = ko.dependentObservable(function () {
//根据密码强度判断第二个格显示的背景色
returnthis.PasswordLevel() <3?this.Ocolor : "#33CC00"
}, viewModel);
$((function () {
ko.applyBindings(viewModel);
}));
</script>
<form name="form1" action="">
输入密码:<input type="text" size="10" data-bind="value:Password, valueUpdate: 'afterkeydown'">
<br>
密码强度:
<table width="217" border="1" cellspacing="0" cellpadding="1" bordercolor="#cccccc"
height="23" style='display: inline'>
<tr align="center" bgcolor="#eeeeee">
<td width="50" id="strength_L" data-bind="style: { backgroundColor: Lcolor }">

</td>
<td width="50" id="strength_M" data-bind="style: { backgroundColor: Mcolor }">

</td>
<td width="50" id="strength_H" data-bind="style: { backgroundColor: Hcolor }">

</td>
</tr>
</table>
</form>
</body>
</html>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章