日期:2014-05-16 浏览次数:20372 次
? ?用javascript校验密码强度级别,可以检测字母、数字和英文键盘符号,strength值越大则密码越安全。正则表达式版本:
?
/* * @return {number} pwdStrength * -101: too short * -102: too long * 1: weak * 2: medium * 3: strong */ var testPwdStrength1 = function(pwdText){ var pwdStrength = 0; if (typeof pwdText === "string") { if (pwdText.length < 8) { // 密码过短 pwdStrength = -101; } else if (pwdText.length > 20) { // 密码过长 pwdStrength = -102; } else { var containsDigitPattern = /^.*?[\d]+.*$/g; var containsLetterPattern = /^.*?[a-zA-Z]+.*$/g; var containsCharPattern = /^.*?[`~@#\$%\^&\*\(\)\-_=\+\\\|;:'",<\.>\/\?].*$/g; if (containsCharPattern.test(pwdText)) { pwdStrength++; } if (containsLetterPattern.test(pwdText)) { pwdStrength++; } if (containsDigitPattern.test(pwdText)) { pwdStrength++; } } } else { // 密码无效 pwdStrength = -404; } return pwdStrength; };?
不使用正则表达式,基于每个密码字符的ascii值的比较的版本:
?
var testPwdStrength2 = function(pwdText) { var pwdStrength = 0; if(pwdText.length < 8) { pwdStrength = -101; // Too short } else if(pwdText.length > 32) { pwdStrength = -102; // Too long } else { var tempCharCode = 0, lowerCaseLetterCounter = 0, upperCaseLetterCounter = 0, digitCounter = 0, signalCounter = 0; for(var i = 0; i < pwdText.length; i++) { tempCharCode = pwdText.charCodeAt(i); if(tempCharCode > 32 && tempCharCode < 127) { // Visible char if(tempCharCode >= 48 && tempCharCode <= 57) {// 0-9 ++digitCounter; } else if(tempCharCode >= 65 && tempCharCode <= 90) {// A-Z ++upperCaseLetterCounter; } else if(tempCharCode >= 97 && tempCharCode <= 122) {// a-z ++lowerCaseLetterCounter; } else { ++signalCounter; } } else { // Invalid char pwdStrength = -404; break; } } if(upperCaseLetterCounter > 0 || lowerCaseLetterCounter > 0) { ++pwdStrength; } if(digitCounter > 0) { ++pwdStrength; } if(signalCounter > 0) { ++pwdStrength; } } return pwdStrength; };?
?
? ?以上代码在chrome/firefox/ie9下测试通过。函数返回值表示密码的组成情况(字母/数字/符号),如果需要确定密码的具体组合情况可以酌情修改上述代码实现。
?