<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="#" type="post" id="registerForm">
用户名:<input type="text" name="userName"/>
密码:<input type="password" name="password"/>
手机号:<input type="text" name="phoneNumber"/>
<button> 提交</button>
</form>
</body>
</html>
<script type="text/javascript">
/* 对条件验证字段(策略模式) */
/* 定义策略对象. */
var strategies = {
isNonEmpty: function (value, errorMsg) {
if (value === '') {
return errorMsg;
}
},
minLength: function (value, length, errorMsg) {
if (value.length < length) {
return errorMsg;
}
},
isMobile: function (value, errorMsg) {
if (!/(1[3|5|8][0-9]{9}$)/.test(value)) {
return errorMsg;
}
}
};
/* 定义上下文 */
var Validator = function () {
this.cache = [];
};
/* 考虑可以有多个验证条件的情况. */
Validator.prototype.add = function (dom, rules) {
var self = this;
for (var i = 0, rule; rule = rules[i++];) {
/* 注意这种写法 */
(function (rule) {
var strategyAry = rule.strategy.split(":");
var errorMsg = rule.errorMsg;
self.cache.push(function () {
var strategy = strategyAry.shift();
strategyAry.unshift(dom.value);
strategyAry.push(errorMsg);
return strategies[strategy].apply(dom, strategyAry);
});
})(rule);
}
};
Validator.prototype.start = function () {
for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
var errorMsg = validatorFunc();
if (errorMsg) {
return errorMsg;
}
}
};
/* 定义场景类 */
var registerForm = document.getElementById('registerForm');
var validataFunc = function () {
var validator = new Validator();
validator.add(registerForm.userName, [{strategy: 'isNonEmpty', errorMsg: '用户名称不能为空'}, {
strategy: 'minLength:6',
errorMsg: '用户名长度不能小于10位'
}]);
validator.add(registerForm.password, [{strategy: 'minLength:6', errorMsg: '密码长度不能小于6位'}]);
validator.add(registerForm.phoneNumber, [{strategy: 'isMobile', errorMsg: '手机号码格式不正确'}]);
var errorMsg = validator.start();
return errorMsg;
};
/* */
registerForm.onsubmit = function () {
var errorMsg = validataFunc();
if (errorMsg) {
alert(errorMsg);
return false;
}
};
</script>
转载于:https://my.oschina.net/u/1579560/blog/638155