2016-06-10 53 views
0

我正在使用Jquery驗證插件來驗證動態窗體。我得到的錯誤消息是想要的,但主要問題是所需的字段是空或不管條件提交按鈕仍然工作。如果必填字段爲空,我無法停止提交。這是我的代碼的一小部分。Jquery驗證插件(.validate)不工作在動態表單(循環窗體)

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", 
      } 
      } 
    }); 
+0

http://stackoverflow.com/questions/24670447/how-to-validate-array-of-inputs-using-validate-plugin-jquery」 – coolguy

+0

解決方案他們只能用於單個數組。我無法找到多維數組的解決方案 – Kais

回答

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 
    } 
}); 
相關問題