js如何驗證密碼強度
更新時間:2020年03月18日 11:17:52 作者:Kevin''''''''''''''''s life
這篇文章主要為大家詳細介紹了js如何驗證密碼強度,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
驗證“密碼強度”的例子很常見,我們注冊新的賬號的時候往往設置密碼,此時就遇到驗證密碼強度的問題了?!懊艽a強度”也就是密碼難易程度的意思。
原理:
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 事件,在鍵盤按鍵被松開時發(fā)生,進行判斷
_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 事件(在鍵盤按鍵被松開時發(fā)生)進行三種判斷,簡單方便。
2. 正則表達式的功能真的很強大。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
JavaScript數組中相同的元素進行分組(數據聚合)groupBy函數詳解
今天在打算從js端時序數據庫TSDB中,按相同的類型的數據排在一起,并且取同一時間段最新的數據,經過查詢這種思想叫做數據聚合,就是返回的數據要根據一個屬性來做計算,這篇文章主要介紹了JavaScript數組中相同的元素進行分組(數據聚合)?groupBy函數,需要的朋友可以參考下2023-12-12

