JQuery.Validate添加动态规则与消息

前端之家收集整理的这篇文章主要介绍了JQuery.Validate添加动态规则与消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。



我有一个表单,我使用jquery.validate.我最初调用validate与一组规则和自定义消息…
  1. $("#formName").validate( {
  2. rules: {
  3. myExistingInput: {
  4. required: true
  5. }
  6. },messages: {
  7. myExistingInput: {
  8. required: "Enter something"
  9. }
  10. },ignore: null,// include hidden fields (see below)
  11. submitHandler: function(form) {
  12. // do stuff
  13. },invalidHandler: function(event,validator) {
  14. // do stuff (some of the fields may have been hidden by a collapsible panel
  15. // if there is an error on one of those fields,expand the panel so the error
  16. // becomes visible)
  17. }
  18. });

后来我动态地添加字段到表单,并添加这些字段的规则…

  1. $("#formName").append(...);
  2.  
  3. $("#newInputName").rules("add",{
  4. required: true,messages: {
  5. required: "Enter something else"
  6. }
  7. });

如果我提交表单,我从jquery.validate中得到一个错误

Exception occured when checking element newInputName,check the
‘messages’ method.TypeError: Unable to get property ‘call’ of
undefined or null reference

在浏览器中调试,我可以看到从“check”函数中抛出的错误,“method”变量设置为“messages”.

如果我从调用规则中删除消息(“添加”,…

  1. $("#newInputName").rules("add",{
  2. required: true
  3. });

它按预期工作,但显然我现在没有自定义错误消息.

我在这里看到很多例子,说明我的语法是正确的.有什么建议么?

BTW:jQuery验证插件 – v1.11.0 – 2/4/2013

解决方法

你的代码似乎正在工作,没有错误,你发布它.

DEMO与DOM准备:http://jsfiddle.net/UZTnE/

DEMO与PageInit& jQuery手机:http://jsfiddle.net/xJ3E2/

  1. $(document).on("pageinit",function () {
  2.  
  3. $('#myform').validate({ // initialize the plugin
  4. rules: {
  5. field1: {
  6. required: true
  7. }
  8. },messages: {
  9. field1: {
  10. required: "Enter something"
  11. }
  12. }
  13. });
  14.  
  15. $('[name*="field"]').each(function () {
  16. $(this).rules('add',{
  17. required: true,messages: {
  18. required: "Enter something else"
  19. }
  20. });
  21. });
  22.  
  23. });

HTML:

  1. <form id="myform">
  2. <input type="text" name="field1" />
  3. <input type="text" name="field2" />
  4. <input type="submit" />
  5. </form>

BTW:

这个…

  1. ignore: null,// include hidden fields

应该…

  1. ignore: [],// include hidden fields

见:jQuery Validate – Enable validation for hidden fields

猜你在找的jQuery相关文章