【问题标题】:jQuery Validation on large form大型表单上的 jQuery 验证
【发布时间】:2013-04-27 11:50:56
【问题描述】:

我正在创建一个包含用户提交给服务器的大型表单的网络应用程序。

此表单具有标准的 jQuery 验证,并且工作正常。 (http://bassistance.de/jquery-plugins/jquery-plugin-validation/)

但是,表单中间的部分需要通过 ajax 调用提交。假设表单的这一部分有一个简单的“添加”按钮——按下添加按钮时是否可以只验证表单的这一部分?

并在正常提交时验证表单的其余部分。我查看了 jQuery Validation api,但什么也没看到。

我想我可以像这样手动调用:

$('#commentForm').validate({
    rules : {
        cname: {
            required: true,
            minlength: 2
        }
    }
}).element("#cname");

不幸的是,这增加了在按下主提交按钮时检查的验证。

任何关于此事的帮助或建议将不胜感激:)

【问题讨论】:

标签: jquery forms jquery-validate


【解决方案1】:

这可能对你有用。 Link to jsfiddle

HTML

  <form id="commentForm" method="post" action="index.php" style="font-family: Georgia">
     <fieldset>
        <legend>The main form</legend>
        <label for="text1">Text 1</label>
        <input type="text" id="text1" name="text1" />
        <br /><br />
        <fieldset id="opt">
           <legend>This section is only rquired when "Add" button is clicked</legend>
           <label for="text2">Text 2</label>
           <input type="text" id="text2" name="text2" />
           <br /><br />
           <button id="add">Add</button>

        </fieldset>
        <br />
        <label for="text4">Text 4</label>

        <input type="text" id="text4" name="text4" />
        <br /><br />
        <input type="submit" id="submit" value="Post Main Form" />
     </fieldset>
  </form>

JavaScript

        $('#commentForm').validate({
           //ignore everything in the sub-form
           ignore: '#opt *',
           rules: {
              text1: {
                 required: true,
                 minlength: 2
              },
              text4: {
                 required: true,
                 minlength: 2
              }
           }
        });

        $('#add').click(function () {

           var txt = $('#text2');

           //here you add validation rules for sub-form elements
           txt.rules('add', {
              required: true
           });

           //here you trigger the validation for elements in subform
           txt.valid();

           /* here you do your ajax stuff */

           return false;
        });

这种方法 jQuery 验证器插件的 ignore 选项以及 .valid() 方法来手动触发元素验证。希望对你有帮助。

这个例子是使用jQuery Validation Plugin - v1.10.0测试的

【讨论】:

  • 我认为这正是我所需要的!我不知道我可以使用插件“忽略”某些元素!非常感谢 Ejay!
猜你喜欢
  • 1970-01-01
  • 2011-07-29
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2011-07-12
  • 2013-10-07
相关资源
最近更新 更多