這篇文章我們來說一個驗證密碼強度的例子,大家在進入一個網站的時候,往往都會先注冊一個賬號,然后輸入密碼,在輸密碼的時候,系統會根據我們輸入的密碼組成的復雜程度來給你的密碼顯示一個密碼強度,一般就是強中弱三種,我們先來說一下密碼驗證的原理,原理明白了,js代碼就好寫了,今天的代碼會用到正則表達式。
首先說一下密碼強度的三種等級是如何劃分的?
弱:一般就是純數字或純小寫字母或者純大寫字母組成的,這種密碼較簡單,所以安全等級為弱。
中:由上述情況中的任意兩種組成的密碼強度為中。
強:上述三種情況都有。
再來說一下表示強中弱的三個div隨著密碼的輸入來顯示對應的強度,首先我們先寫一個class名為active的樣式,顏色隨便寫一下,然后判斷完輸入的密碼強度等級之后,把對應的強度的div的class名改為active就可以了。
寫代碼吧:
html:
<div id = 'div1'> <input type="text" id = 'password' placeholder="密碼"/> <div id = 'intension'> <div>弱</div> <div>中</div> <div>強</div> </div> </div>
css:
<style>
#div1{width: 350px; height: 200px; background-color: orange; border: 1px solid black; margin: 100px auto; text-align: center; padding-top: 50px}
#intension div{background-color: gray; width: 80px; height: 20px; text-align: center; line-height: 20px; margin: 5px; float: left; }
#intension{width: 270px; margin-left: 40px}
#password{width: 300px; height: 30px; font-size: 18px;}
#intension .active{background-color: pink}
</style>
js代碼:
萬年不變的獲取id:
var oPassword = document.getElementById("password");
var oDiv = document.getElementById("intension");
var nodes = oDiv.getElementsByTagName("div");
然后用正則表達式來判斷密碼強度
oPassword.onkeyup = function(){
var oValue = oPassword.value;
for(var i = 0; i < nodes.length; i++){
nodes[i].className = '';
}
if(/\d/.test(oValue) && /[a-z]/.test(oValue) && /[A-Z]/.test(oValue)){
nodes[2].className = "active";
}else if(/^\d+$/.test(oValue) || /^[A-Z]+$/.test(oValue) || /^[a-z]+$/.test(oValue)){
nodes[0].className = "active";
}else{
nodes[1].className = "active";
}
}
這樣我們的驗證密碼強度就完成了!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。