JS数据校验

博客转载了2019年独角兽企业重金招聘Python工程师的标准,链接为https://my.oschina.net/fusublog/blog/1934489 。
/**
 * @Author:WuChao
 * @Description:校验策略
 * @date:23:23 2018/8/21
 */
var strategies = {
    isNotEmpty: function (value, errorMsg) {
        if (value === '') {
            return errorMsg;
        }
    },
    minLength: function (value, length, errorMsg) {
        if (value.length < length) {
            return errorMsg;
        }
    },
    isMobile: function (value, errorMsg) {
        if (!/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(value)) {
            return errorMsg;
        }
    }
};


/**
 * @Author:WuChao
 * @Description:保存校验规则
 * @date:23:42 2018/8/21
 */
var Validator = function () {
    this.cache = [];
};


/**
 * @Author:WuChao
 * @Description:校验函数的初始化
 * @date:11:45 2018/8/27
 */
Validator.prototype.add = function (dom, rule, errorMsg) {
    var ary = rule.split(':');
    this.cache.push(function () {
        var strategy = ary.shift();
        ary.unshift(dom.value);
        ary.push(errorMsg);
        return strategies[strategy].apply(dom, ary);
    });
};


/**
 * @Author:WuChao
 * @Description:启动校验
 * @date:11:46 2018/8/27
 */
Validator.prototype.start = function () {
    for (var i = 0, validateFunc; validateFunc = this.cache[i++];) {
        var msg = validateFunc();
        if (msg) {
            return msg;
        }
    }
};

var registerForm = $("#registerForm")[0];

var validateFunc = function () {
    var validator = new Validator();
    validator.add(registerForm.userName, 'isNotEmpty', '用户名不能为空');
    validator.add(registerForm.password, 'minLength:6', '密码长度不能少于6位');
    validator.add(registerForm.phoneNumber, 'isNotEmpty', '手机号格式不正确');
    var errorMsg = validator.start();
    return errorMsg;
};

registerForm.onsubmit = function () {
    var errorMsg = validateFunc();
    if (errorMsg) {
        alert(errorMsg);
        return false;
    }
}


转载于:https://my.oschina.net/fusublog/blog/1934489

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值