密碼等級:至少包含字母、大小寫數字、字元中的兩種 JS實現方案

來源:互聯網
上載者:User

標籤:des   http   ar   io   os   使用   sp   for   strong   

前言

密碼,如果設定的太簡單,很容易就被攻破,所以很多網站將密碼設定的要求設定的挺嚴格,一般是字母、數字、字元3選2,區分大小寫。對於設定得太簡單的密碼,予以錯誤提示。或者予以密碼等級(低中高)顯示,讓使用者佈建進階密碼。那如何利用JS實現呢?

代碼

連結:https://gist.github.com/xuanfeng/a44f20cb4569d5b4cd5e

 
1234567891011121314151617181920212223242526272829 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)

驗證規則:數字、大寫字母、小寫字母、特殊字元

函數結果:返回密碼中包含的規則數

運行例子:

 
12 passwordLevel("123456")           //返回1passwordLevel("Abc‘123456")    //返回4

 

結合jquery.validate.js使用

 

 
123456789101112131415161718192021222324 // 添加驗證方法:至少包含兩種規則$.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"        //再次填寫密碼需一致        }    } });

 

密碼等級:至少包含字母、大小寫數字、字元中的兩種 JS實現方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.