Blame view

public/js/passport/password-check.js 1.75 KB
1 2
'use strict';
lijing authored
3
let config = {
4 5 6 7 8 9 10 11 12 13 14 15 16 17
    rules: [
        {method: 'required', param: []},
        {method: 'lte', param: [20]},
        {method: 'gte', param: [6]},
        {method: 'charLimit', param: []}
    ],
    msgs: {
        required: '由字母、数字组合,不能包含特殊字符',
        lte: '长度须在6-20个字符之间',
        gte: '长度须在6-20个字符之间',
        charLimit: '密码须为字母和数字组合'
    }
};
lijing authored
18
let validators = {
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    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) {
lijing authored
37
    let rules = config.rules,
38 39 40
        msgs = config.msgs,
        i, ruleLen;
lijing authored
41
    let name, param, errorMsg = '', pass = true;
42 43 44 45 46 47 48 49 50 51

    // 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) {
52
            errorMsg = msgs[name];
53 54 55 56
            break;
        }
    }
57 58
    if (callback) {
        pass ? callback({valid: true}) : callback({valid: false, msg: errorMsg}); // eslint-disable-line
59 60
    }
61 62 63 64 65 66 67 68 69 70 71 72 73 74
    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;