/**
* @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