2012-10-14 48 views
1

作爲更大的jQuery驗證表單的一部分,我有一些輸入只需要在按鈕按下時進行驗證。例如輸入項目到一個列表:jQuery驗證單個元素和規則

<form class="validate"> 
    // ...... 
     validated form elements on submit 
    // ...... 

    <select multiple="multiple" id="itemList" size="5"><select> 
    <input type="text" id="newItem" name="newItem"/> 
    <button type="button" id="addItem">add</button> 

    // ...... 
     validated form elements on submit 
    // ...... 
    <button type="submit">Submit Form</button> 
</form> 

<script> 
    $(document).on("click", "#addItem", function(e){ 
     if($("form.validate").validate({}).element("#newItem")){ 
      //Code to add valid item to the list 
     } 
    }); 
</script> 

我不想使用輸入的類的方式來分配的規則,因爲這將意味着它會被驗證爲主要形式的一部分,但如果我叫驗證形式爲$([form]).validate({rules ..})。element([element])它們被忽略。

我得到這個工作的唯一方法是在驗證和規則(「刪除」,規則)之前使用規則(「添加」,規則)。

<script> 
    $(document).on("click", "#addItem", function(e){ 
     $("#newItem").rules("add", { 
      required: true, 
      minlength: 2, 
      messages: { 
       required: "Required input", 
       minlength: jQuery.format("Please, at least {0} characters are necessary") 
      } 
     }); 

     $("form.validate").validate().element("#newItem"); 

     $("#newItem").rules("remove"); 
    }); 
</script> 

然而,這似乎相當不雅,所以如果任何人都可以告訴我,我要去哪裏錯了,這將是盛大:)

+3

爲什麼要檢查,如果($(「form.validate」) .validate({})。element(「#newItem」))如果你想檢查表單是否有效或不使用$(「form.validate」)。valid()這個方法返回true或false,另一個返回驗證對象。 –

+0

@ prog-mania在這一點上,我不需要知道整個表單是否有效,我只想驗證正在使用的單個輸入來填充表單的其他元素。 – Carlos

回答

0
<script> 
    $(document).on("click", "#addItem", function(e){ 
     var _validateSingleField=$('form.validate').validate().element('#newItem'); 

     if(_validateSingleField){ 
      //Code to add valid item to the list 
     } 
    }); 
</script>