Jquery Validation插件(.validate)无法在动态表单中工作(循环形式)

时间:2016-06-10 05:45:24

标签: javascript jquery forms jquery-validate

我正在使用Jquery验证插件来验证动态表单。我收到了所需的错误消息,但主要问题是所需的字段是否为空,无论条件提交按钮仍然有效。如果必填字段为空,我无法停止提交。这是我的一小段代码。

HTML:

<form class="pa-form" action="confirmed" method="post" id="my-form">
    <fieldset>
        <?php for($i=1;$i<=3;$i++){ ?>
        <div class="flabel-control">
          <input data-toggle="floatLabel" data-value="" name="myForm[first_name][]" class="firstname form-control" type="text" id="first-name<?=$i?>" required      placeholder="First name" spellcheck="false">
         </div>
        <div class="flabel-control">
          <input data-toggle="floatLabel" data-value="" name="myForm[last_name][]" class="firstname form-control" type="text" id="last-name<?=$i?>" required        placeholder="Last name" spellcheck="false">
         </div>
        <br>
        <?php };?>
           <div class="btn-holder">
            <input type="submit" id="submitBtn" class="btn btn-default text-uppercase" value="Confirm">
        </div>
    </fieldset>
</form>

JS:

$("#my-form").validate({
          validClass: "valid",
          errorClass: "error",
          rules: {
            'myForm[first_name][]': "required",
            'myForm[last_name][]': "required",
          },
          messages: {
            'myForm[first_name][]': "First name is required",
            'myForm[last_name][]': "Last name is required",
            }
          }
    });

1 个答案:

答案 0 :(得分:1)

jquery-validate要求每个元素都有唯一的名称。所以将for循环索引放入名称中。

    <?php for($i=1;$i<=3;$i++){ ?>
    <div class="flabel-control">
      <input data-toggle="floatLabel" data-value="" name="myForm[first_name][<?=$i?>]" class="firstname form-control" type="text" id="first-name<?=$i?>" required placeholder="First name" spellcheck="false">
     </div>
    <div class="flabel-control">
      <input data-toggle="floatLabel" data-value="" name="myForm[last_name][<?=$i?>]" class="firstname form-control" type="text" id="last-name<?=$i?>" required placeholder="Last name" spellcheck="false">
     </div>
    <br>
    <?php };?>

您不需要在rules中专门列出元素,因为插件会自动处理元素中的required属性。但如果你愿意,你可以这样做:

var rules = {}, messages = {};
for (var i = 1; i <= 3; i++) {
    rules['myForm[firstname][' + i + ']'] = 'required';
    messages['myForm[firstname][' + i + ']'] = 'First name is required';
    rules['myForm[lastname][' + i + ']'] = 'required';
    messages['myForm[lastname][' + i + ']'] = 'Last name is required';
}
$("#my-form").validate({
      validClass: "valid",
      errorClass: "error",
      rules: rules,
      messages: messages
    }
});