password-check.js 1.75 KB
'use strict';

var config = {
    rules: [
        {method: 'required', param: []},
        {method: 'lte', param: [20]},
        {method: 'gte', param: [6]},
        {method: 'charLimit', param: []}
    ],
    msgs: {
        required: '由字母、数字组合,不能包含特殊字符',
        lte: '长度须在6-20个字符之间',
        gte: '长度须在6-20个字符之间',
        charLimit: '密码须为字母和数字组合'
    }
};

var validators = {
    required: function(val) {
        return !!val.length;
    },

    gte: function(val, param) {
        return val.length >= param;
    },

    lte: function(val, param) {
        return val.length <= param;
    },

    charLimit: function(val) {
        return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(val);
    }
};

function validate(val, callback) {
    var rules = config.rules,
        msgs = config.msgs,
        i, ruleLen;

    var name, param, errorMsg = '', pass = true;

    // apple rule one by one;
    for (i = 0, ruleLen = rules.length; i < ruleLen; i++) {
        name = rules[i].method;
        param = rules[i].param.concat();
        param.unshift(val);

        pass = validators[name].apply(this, param);

        if (!pass) {
            errorMsg = msgs[name];
            break;
        }
    }

    if (callback) {
        pass ? callback({valid: true}) : callback({valid: false, msg: errorMsg}); // eslint-disable-line
    }

    return pass;
}

// test
/* eslint-disable */
// validate('1234567', function(result) {console.log(result)})
// validate('12345', function(result) {console.log(result)});
// validate('a'.repeat(21), function(result) {console.log(result)});
// validate('1abcdefg', function(result) {console.log(result)});
/* eslint-enable */


module.exports = validate;