<!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>
转载于:https://www.cnblogs.com/diligenceday/p/3433761.html