JQuery.Validate添加带有消息的动态规则 [英] JQuery.Validate adding dynamic rules with messages
问题描述
我有一个使用jquery.validate的表单.我最初使用一组规则和自定义消息来调用validate ...
I have a form on which I am using jquery.validate. I initially call validate with a set of rules and custom messages...
$("#formName").validate( {
rules: {
myExistingInput: {
required: true
}
},
messages: {
myExistingInput: {
required: "Enter something"
}
},
ignore: null, // include hidden fields (see below)
submitHandler: function(form) {
// do stuff
},
invalidHandler: function(event, validator) {
// do stuff (some of the fields may have been hidden by a collapsible panel
// if there is an error on one of those fields, expand the panel so the error
// becomes visible)
}
});
后来,我将字段动态添加到表单中,并且还为这些字段添加了规则...
Later, I dynamically add fields to the form, and add rules for those fields too...
$("#formName").append(...);
$("#newInputName").rules("add", {
required: true,
messages: {
required: "Enter something else"
}
});
如果我随后提交表单,则会在jquery.validate ...中收到错误消息.
If I then submit the form, I get an error from within jquery.validate...
检查元素newInputName时发生异常,请检查 'messages'method.TypeError:无法获得属性"call" 未定义或空引用
Exception occured when checking element newInputName, check the 'messages' method.TypeError: Unable to get property 'call' of undefined or null reference
在浏览器中进行调试时,我可以看到错误是从检查"函数中引发的,并且方法"变量设置为消息".
Debugging in the browser, I can see the error is being thrown from within the "check" function, and that the "method" variable is set to "messages".
如果我从规则调用中删除了消息("add",...
If I remove the messages from the call to rules("add",...
$("#newInputName").rules("add", {
required: true
});
它可以按预期工作,但是显然我现在没有自定义错误消息.
it works as expected, but obviously I now have no custom error messages.
我在SO上看到了很多例子,这些例子表明我的语法是正确的.有什么建议吗?
I have seen many examples here on SO indicating that my syntax is correct. Any suggestions?
BTW:jQuery验证插件-v1.11.0-2/4/2013
BTW: jQuery Validation Plugin - v1.11.0 - 2/4/2013
推荐答案
您发布的代码似乎正常运行,没有错误.
Your code seems to be working, without error, as you posted it.
具有DOM就绪的DEMO: http://jsfiddle.net/UZTnE/
DEMO with DOM ready: http://jsfiddle.net/UZTnE/
DEMO与PageInit& jQuery Mobile: http://jsfiddle.net/xJ3E2/
DEMO with PageInit & jQuery Mobile: http://jsfiddle.net/xJ3E2/
$(document).on("pageinit", function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true
}
},
messages: {
field1: {
required: "Enter something"
}
}
});
$('[name*="field"]').each(function () {
$(this).rules('add', {
required: true,
messages: {
required: "Enter something else"
}
});
});
});
HTML :
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
顺便说一句:
这个...
ignore: null, // include hidden fields
应该是...
ignore: [], // include hidden fields
请参阅: jQuery Validate-对隐藏字段启用验证
这篇关于JQuery.Validate添加带有消息的动态规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!