2014-03-28 105 views
0

如何在使用jQuery验证插件时验证一组复选框?使用jQuery验证插件验证一组复选框

我用于text的代码如下,但是它是如何处理一组复选框的?

<form id="newItem" action="formProcess.php" method="post"> 
    <input type="text" class="itemTitle" name="itemTitle" value="" autocomplete="off"><br> 
    <label for="itemTitle" generated="true" class="error itemTitle" style=""></label><br> 
    <input type="checkbox" name="country[]" value="US" class="destinations"><br> 
    <input type="checkbox" name="country[]" value="GB" class="destinations"><br> 
    <input type="checkbox" name="country[]" value="CA" class="destinations"><br> 
    <input type="checkbox" name="country[]" value="SE" class="destinations"><br> 
    <label for="destinations" generated="true" class="error destinations" style=""></label><br> 
<input type="submit" name="Submit" value="Submit"> 
</form>; 

$("#newItem").validate({ 
    rules: { 
     itemTitle: { 
      required: true, 
      minlength: 3, 
      maxlength: 60 
     }, 
    // How is it done for a group of check boxes? 
    // I'd like at least 1 destination to be selected, and a maximum of 3. This cannot be left blank. 


    messages: { 
     itemTitle: { 
      required: "Please enter a valid name", 
      minlength: "Minimum length required is 3 characters", 
      maxlength: "Maximum length allowed 51 characters" 
     }, 
    }, 
submitHandler: function() { 
// Other code follows 

回答

1

试试这个

$("#newItem").validate({ 
    rules: { 
     "country[]": { 
      required: true, 
      minlength: 1, 
      maxlength: 3 
     } 
    }, 
    messages: { 
     "country[]": { 
      required: "Check atleast 1", 
      minlength: "Min 1", 
      maxlength: "Max only 3" 
     } 
    } 

}); 

DEMO