您的位置:首页 > 其它

使用策略模式进行简单的form验证

2017-01-15 20:52 363 查看
<h1>使用策略模式进行简单的form验证</h1>
<form action="" method="post" id="registForm" novalidate>
请输入用户名:<input type="text" name="userName" />
<br />
请输入密码:<input type="text" name="password" />
<br />
请输入手机号:<input type="text" name="phoneNumber" />
<br />
<input type="submit" value="提交" />
</form>
<script>

var stategies = {

required: function( value, errorMsg ){
if( value == "" ){
return errorMsg;
}
},

minLength: function( value, length, errorMsg ){
if( value.length < length ){
return errorMsg;
}
},

isMobile: function( value, errorMsg ){
if( !( /^1[34578]\d{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 stategies[ strategy ].apply( dom, strategyAry );
} )
}( rule ) )
}
},

start: function(){

for( var i = 0, validatorFunc; validatorFunc = this.cache[ i++ ]; ){
var errorMsg = validatorFunc();
if( errorMsg ){
return errorMsg;
}
}
}
};

var registForm = document.getElementById( "registForm" );

var validateFunc = function(){
var validator = new Validator();

validator.add( registForm.userName, [{

strategy: "required",
errorMsg: "用户名不能为空"
},{

strategy: "minLength:3",
errorMsg: "用户名长度不能小于3位"
}]);

validator.add( registForm.password, [{

strategy: "minLength:6",
errorMsg: "密码长度不能小于6位"
}]);

validator.add( registForm.phoneNumber, [{

strategy: "isMobile",
errorMsg: "手机号码格式不正确"
}]);

var errorMsg = validator.start();
return errorMsg;
};
var errorMsg = validateFunc();

registForm.onsubmit = function(){
var errorMsg = validateFunc();
if( errorMsg ){
console.log(errorMsg);
return false;
}
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐