您的位置:首页 > Web前端 > JavaScript

JS模式:策略模式,感觉就是一个闭包存储信息,然后是加一些验证方法--还看了老半天

2013-11-20 15:53 525 查看
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
var varlidator;
varlidator = {
validate: function(value, type){
var value = value;
var type = type;
switch(type){
case 'isnonEmpty' : {
//..yuju
return true;
}
case 'isNumber' : {
//..yuju
return true;
}
case 'isAlphaNum' : {
//..yuju
return true;
}
default :{
return 'someting'
}
}
}
};
alert(validator.validate('123','isNonEmpty')) ; //有点像命令行模式;

var validator = {
types : {},
messages : [],
config : {},
validate : function(data){
var i, msg , type, checker, result_ok;
this.messages = [];
for(var i in data){
if(data.hasOwnProperty(i)){
type = this.config[i];
checker = this.types[type];

if(!type){
continue;
};
if(!checker){
throw{
name : 'ValidationError',
message : 'no handler to validate type '+ type
}
};

result_ok = checker.validate(data[i]);
if( !result_ok ){
msg = 'wrong' + checker.instructions;
this.message.push( msg );
}
}
};
return this.hasErrors();
},
hasErrors : function(){
return this.message.length !== 0
}
};

validator.types.inNonEmpty = {
validate : function(value){
return value !== '';
},
instructions : 'value can“t be null'
};
validator.types.isNumber = {
validate : function(value){
return !isNaN( value )
},
instructions : '必须是数字哦'
};
validator.types.isAlphaNum = {
validator : function(value){
return !/[^a-z0-9]/i,test(value);
},
instructions : '必须是数字哦'
};

var data = {
first_name : 'xx',
last_name : '00',
age  : 26,
username : 'qihao'
};
validator.config = {
first_name : 'isNumber',
age : 'isNonEmpty',
username : 'isAplhaNum'
};
validator.validate( data );
validator.hasErrors();
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐