JavaScript 密码复杂度判断函数

Posted by Sir0xb on 2012-12-03 14:41:11 +0800
function Evaluate(word, config){
    var conf = config || {};
    var l = conf.length || 8;                            //默认判断长度8
    var cont = conf.count || 2;                          //默认复杂度2种
    var key = conf.eye || false;                         //默认大小写不敏感
    var msgLength = conf.msgLength || "密码过短!";        //默认密码过短提示
    var msgCount = conf.msgCount || "种类太少!";          //默认种类不够提示
    var msg = conf.fun || _msg;                         //默认消息提示空函数
 
    function _msg(msg){
        //console.log(msg);
    }
 
    if(word.length < l){
        msg(msgLength);
        return false;
    }else{
        var check = 0;
        if(key){
            check = word.match(/[a-z](?![^a-z]*[a-z])|[A-Z](?![^A-Z]*[A-Z])|\d(?![^\d]*\d)|[^a-zA-Z\d](?![a-zA-Z\d]*[^a-zA-Z\d])/g).length;
        }else{
            check = word.match(/[a-zA-Z](?![^a-zA-Z]*[a-zA-Z])|\d(?![^\d]*\d)|[^a-zA-Z\d](?![a-zA-Z\d]*[^a-zA-Z\d])/g).length;
        }
        if(check < cont){
            msg(msgCount);
            return false;
        }
    }
    return true;
}

使用方法(第二个参数可有可无,也可选择性填入):

Evaluate("要判断的字符串", {
    length: 8,                   //要限定的长度
    count: 2,                    //复杂度,至少要两种混合
    eye: true,                   //是否大小写敏感
    msgLength: "老兄密码太短了",   //密码过短时的提示
    msgCount: "老兄密码要混搭",    //密码种类太少的提示
    fun: alert                   //要调用的提示函数,可以是 alert console.log function(xx){xxx}
});