帮助jquery验证插件和复选框

时间:2011-07-29 20:23:09

标签: jquery jquery-validate

我有一个复选框组,我需要唯一地命名它以分别在数据库中存储值。 但是,使用jquery validate插件,我无法验证名称不同的组。

<label>Would you like to compete?</label>
      <input type="checkbox"  name="compete1" value="2" class="competecheckbox" >
      <label for="compete_no">No</label>
      <input type="checkbox" name="compete2" value="1" class="competecheckbox">
      <label for="compete_yes">Yes</label>
      <div id="competeyes">
        <label class="competeyestxt" hidden=true>Which Location?</label>
        <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true">
        </textarea>
      </div>

我尝试添加

$.validator.addClassRules(
"competecheckbox", {required: true, minlength: 1});

这种方法有效,但它显示2条错误消息。 每个匹配类'competcheckbox'一个。

问题在于,即使用户选择了competition1,仍然会为competition2保留验证错误消息。

当用户选择至少一个复选框时,如何清除这两条消息?

感谢

2 个答案:

答案 0 :(得分:10)

我最终得到了类似的东西:

 <label>Would you like to compete?</label>
      <input type="checkbox"  name="compete[]" value="2" class="competecheckbox" >
      <label for="compete_no">No</label>
      <input type="checkbox" name="compete[]" value="1" class="competecheckbox">
      <label for="compete_yes">Yes</label>
      <div id="competeyes">
        <label class="competeyestxt" hidden=true>Which Location?</label>
        <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true">
        </textarea>
      </div>


When the form is submitted you get values in an array as compete[1], compete[2] etc.
I didn't know that you could do an empty array for form variable names.
Every day I find out how ignorant I am :)

验证规则看起来像

$('#survey').validate( {
    rules: {
        "compete[]": {
            required: true,
            minlength: 1
        }
  });

The quotes around "compete[]" are required as explained here:

http://docs.jquery.com/Plugins/Validation/Reference#Fields_with_complex_names_.28brackets.2C_dots.29

答案 1 :(得分:4)

我会使用groups选项。此选项允许您对所需的input进行分组:

$("#form").validate({
    groups: {
        competecheckbox: "compete1 compete2"
    },
    errorPlacement: function ($error, $element) {
        if ($element.attr("name") === "compete1" || $element.attr("name") === "compete2") {
            $error.insertAfter("label[for='compete_yes']");
        } else {
            $error.insertAfter($element);
        }
    }
});

示例: http://jsfiddle.net/z37Sj/


备注:

  • errorPlacement用于确定邮件是否为分组字段之一。如果是,则在“是”复选框后插入错误(这很容易更改)。否则,它将在元素之后采用其默认位置。
  • groups选项用于指定名为competecheckbox的组,其中包含compete1compete2。这两个字段一起验证。