Skip to content

Instantly share code, notes, and snippets.

@Janking
Created May 27, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Janking/4e9695b566144e5db93b to your computer and use it in GitHub Desktop.
Save Janking/4e9695b566144e5db93b to your computer and use it in GitHub Desktop.
策略模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" id="form">
<input type="text" name="userName">
<input type="text">
<input type="submit" value="click">
</form>
<script type="text/javascript">
/*************************策略对象*****************************/
var strategies = {
isNonEmpty: function(value, errorMsg) {
if (value.length === 0) {
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;
}
}
};
/*************************Validator类*****************************/
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('form');
var validateFunc = function() {
var validator = new Validator();
validator.add(registerForm.userName, [{
strategy: 'isNonEmpty',
errorMsg: '用户名不能为空'
}, {
strategy: 'minLength:10',
errorMsg: '用户名长度不能小于10位'
}]);
var errorMsg = validator.start();
return errorMsg;
};
registerForm.onsubmit = function(event) {
event.preventDefault();
console.log(validateFunc())
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment