The examples in this article describe two methods of using JS to implement password levels that contain at least letters, uppercase and lowercase numbers, and characters. Share it with everyone for your reference. The details are as follows:
Foreword
Passwords can be easily broken if they are set too simply, so many websites set very strict requirements for passwords, usually 2 out of 3 letters, numbers, and characters, and are case-sensitive. If the password is set too simple, an error message will be given. Or display the password level (low, medium and high) to allow users to set advanced passwords. So how to implement it using JS?
The implementation code is as follows:
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; } }
Use
Normal use
Usage syntax: passwordLevel(string)
Validation rules: numbers, uppercase letters, lowercase letters, special characters
Function result: Returns the number of rules contained in the password
Running example:
passwordLevel("123456") //返回1 passwordLevel("Abc'123456") //返回4
Use in combination with jquery.validate.js:
//添加验证方法:至少包含两种规则 $.validator.addMethod("strongPsw",function(value,element){ if(passwordLevel(value)==1){returnfalse;} returntrue },"格式不符合"); //开始验证 $(".form").validate({ rules:{ pwd:{ required:true, //必填 minlength:6, //最小长度 maxlength:32, //最大长度 strongPsw:true, //密码强度 }, repwd:{ required:true, minlength:6, maxlength:32, equalTo:"#pwd" //再次填写密码需一致 } } });
Friends who are interested in password generation and strength detection can also refer to the online tool:
Password security online detection
Short link (short URL) online generation tool
I hope this article will be helpful to everyone’s JavaScript programming design.