如果我执行以下代码,我得到一个无法转换为对象错误; 未捕获的异常:TypeError:无法将'validation.messages.field'转换为对象
$.fn.validate = function(validation) {
$.each(validation.rules, function(field, fieldRules){
$.each(fieldRules, function(rule, ruleValue){
var fieldValue = $('[name=' + field + ']').val();
if (eval(rule + '(fieldValue, ruleValue)') == false){
alert(validation.rules.field.rule);
return false;
}else{
return true;
};
});
});
}
问题是
alert(validation.messages.field.rule);
'field'='persoon_voornaam'和'rule'='required'
并且validation.messages.persoon_voornaam.required
工作正常。
我做错了什么?
验证是一个如下所示的JSON:
{
rules: {
persoon_voornaam: {
required: true,
minlength: 5,
},
postcode_bestemming: {
required: true,
minlength: 7,
},
},
messages: {
persoon_voornaam: {
required: 'Dit veld is verplicht',
minlengt: 'Dit veld moet minstens 5 lang zijn',
},
}
}
答案 0 :(得分:1)
必须是:
alert(validation.rules[field][rule])
澄清:
validation.rules
是一个对象,而field
是一个字符串为'persoon_voornaam'
的变量。
validation.rules.persoon_voornaam
是一个对象,与validation.rules['persoon_voornaam']
相同。
答案 1 :(得分:1)
已经给出了问题的答案。我想提出一个改进的代码版本,使代码更可重用(否则不需要将它附加到jQuery对象)。
eval
是邪恶的。您必须使用名为required
和minlength
的函数污染全局命名空间。以下代码尝试解决这些问题:
$.fn.validate = (function() {
var validators = {
'required': function(value, ruleValue) {
/*...*/
},
'minlength': function(value, ruleValue) {
/*...*/
}
};
return function(validation, config) {
return this.each(function() {
var errors = [];
var $element = $(this);
$.each(validation.rules, function(field, fieldRules){
$.each(fieldRules, function(rule, ruleValue){
var fieldValue = $element.find('[name=' + field + ']').val();
if (rule in validators && validators[rule].call(null, fieldValue, ruleValue) === false){
var message = (field in validation.messages && rule in validation.messages[field]) ? validation.messages[field][rule] : '';
errors.push([field, rule, message])
return false;
}
});
});
// the following part could be written shorter as
// var cb = erros.length > 0 ? 'onerror' : 'onsuccess';
// if(typeof config[cb] === 'function') {
// config[cb](errors);
// }
// but it will pass an empty array to success (which is not a problem
// I just though it might be confusing)
if(erros.length > 0) {
if(typeof config.onerror === 'function') {
config.onerror(errors);
}
}
else {
if(typeof config.onsuccess === 'function') {
config.onsuccess();
}
}
});
}
}());
然后你可以用以下方法调用该函数:
$('#yourFormId').validate(valditation, {
onerror: function(errors) {
// do something with errors
},
onsuccess: function() {
// do something else
}
});
它只会验证表单中的字段。