validation.js 2.38 KB
var common = require('../../common');

var makeValidate = {
    reg: function(val, reg) {
        return reg.test(val);
    },
    minLength: function(val, l) {

        return common.getStrLength(val) >= l;
    },
    maxLength: function(val, l) {

        return common.getStrLength(val) <= l;
    },
    isNumber: function(val, bl) {
        return bl && !isNaN(parseInt(val, 10));
    },
    necessary: function(val, bl) {
        return bl && common.getStrLength(val) > 0;
    },
    addr: function(val) {
        // 完整的地址应该是长度为三的数组
        return val.split(',').length === 3;
    },
    equal: function(val, val2) {
        return val === val2;
    }
};

function showMsg(obj) {
    var text = obj.msg || '数据格式有问题,请检查';
    var m = '<span class="error-msg validate-msg"><span class="iconfont">&#xe60c;</span>' + text + '</span>';

    var curMsg = $(obj.el).next('.validate-msg');

    if (curMsg.length > 0) {
        curMsg.remove();
    }

    if (obj.err) {
        $(obj.el).after(m);
    } else {
        m = '<span class="correct-msg validate-msg"><span class="iconfont">&#xe610;</span>';
        $(obj.el).after(m);
    }
}

/*
 *  根据conditions规则验证selector的值
 *  @param {String} selector jquery选择器
 *  @param {Object} conditions 验证对象
 *  @retrun {Boolen} true/false
 */
/*
 * @example:
 * validate.do('#user-name', {
 *     minLength: 3,
 *     reg: /\w/,
 *     necessary: true
 * })
 */
function validate(selector, conditions) {
    var pass = true;
    var $el = $(selector);
    var c;

    for (c in conditions) {
        if (makeValidate[c] && !makeValidate[c].call(null, $el.val(), conditions[c])) {
            pass = false;


            showMsg({
                el: selector,
                err: true,
                msg: conditions.errMsg
            });

            return false;

        } else if (c !== 'errMsg') {
            showMsg({
                el: selector
            });
        }
    }

    return pass;
}

function validateAddr(val, conditions) {
    var pass = true;

    if (makeValidate.addr(val)) {
        showMsg({
            el: conditions.el
        });
    } else {
        pass = false;
        showMsg({
            el: conditions.el,
            err: true,
            msg: conditions.errMsg
        });
    }

    return pass;
}

module.exports = {
    start: validate,
    addr: validateAddr
};