尝试这个:
var __REGEXINT__ = '__REGEXINT__',
var __REGEXCEP__ = '__REGEXCEP__';
var __REGEXMAIL__ = '__REGEXMAIL__';
var validator = {
_targetErrors : '#sectionErrors',
setError: function(msg){
var message = '<p>{message}</p>'.replace('{message}', msg);
$(this._targetErrors).append(message)
},
__renderInputs : function(__inputs__){
function __getValueOfTarget(target, delimitator){
if(!target)
return false;
if(typeof target == "string")
return $(target).val();
else if(typeof target == "object"){
var _return_ = [];
if(!delimitator)
delimitator = '';
for(var id in target)
_return_.push(__getValueOfTarget(target[id]));
return _return_.join(delimitator);
}
return false;
}
var __return__ = {};
var __error__ = false;
for(name in __inputs__){
var input = __inputs__[name];
var value = __return__[name] = __getValueOfTarget(input.target, input.delimitator);
var foundError = false;
if(!input.validator){
__return__[name] = value;
continue;
} else {
for(var validatorID in input.validator){
if(foundError)
continue;
switch(input.validator[validatorID]){
case 'empty':
if(value == ""){
__error__ = foundError = true;
this.setError(input.validator_error[ validatorID ]);
continue;
}
break;
case __REGEXINT__:
if(!/^(\d+)$/.test(value)){
__error__ = foundError = true;
this.setError(input.validator_error[ validatorID ]);
continue;
}
break;
case __REGEXCEP__:
if(!/^(\d{5}\-\d{3})$/.test(value)){
__error__ = foundError = true;
this.setError(input.validator_error[ validatorID ]);
continue;
}
break;
case __REGEXCEP__:
if(!/^(\d{5}\-\d{3})$/.test(value)){
__error__ = foundError = true;
this.setError(input.validator_error[ validatorID ]);
continue;
}
break;
case __REGEXMAIL__:
if(!/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(value)){
__error__ = foundError = true;
this.setError(input.validator_error[ validatorID ]);
continue;
}
break;
}
}
}
}
return (__error__) ? false : __return__
}
}
var __inputs__ = {
id:{
target:"#id_terminal",
validator:["empty", __REGEXINT__ ],
validator_error:[
"Por favor insira a ID do terminal.",
"Por favor insira uma ID valida."
]
},
name:{
target:"#name",
validator:["empty"],
validator_error:["Por favor insira o nome do estabelecimento."]
},
uf:{
target:"#uf",
validator:["empty"],
validator_error:["Por favor insira o estado."]
},
mail:{
target:"#mail",
validator:["empty", __REGEXMAIL__],
validator_error:["Por favor insira um e-mail.", "Por favor insira um e-mail valido"]
},
cep:{
target:[".cep", ".cep2"],
delimitator:'-',
validator:["empty", __REGEXCEP__ ],
validator_error:[
"Por favor insira o cep.",
"Por favor insira um cep valido."
]
}
}
$('#myform').submit(function() {
if(!validator.__renderInputs(__inputs__))
return false;
});