Is it possible to validate an entire clas开发者_C百科s of elements in a form using jQuery.validate? I know that you can assign rules to elements by name, but can you select those elements by class as well? I have a form on my site that doesn't need anything except required
rules, and it's a little clunky to have to type out EVERY single field, especially when dealing with the messages
object!
Here's my code:
<div id="al_address" class="al_account-settings left">
<h2 class="gold alternate1">ADD A NEW ADDRESS</h2>
<form method="POST" action="#" >
<table>
<tr>
<th><label for="name">* address name</label></th>
<td><input type="text" class="al_required" name="name"></td>
</tr>
<tr>
<th><label for="first_name">* first name</label></th>
<td><input type="text" class="al_required" name="firstName"></td>
</tr>
<tr>
<th><label for="last_name">* last name</label></th>
<td><input type="text" class="al_required" name="lastName"></td>
</tr>
<tr>
<th><label for="address1">* street address</label></th>
<td><input type="text" class="al_required" name="address1"></td>
</tr>
<tr>
<th><label for="address2">address 2</label></th>
<td><input type="text" name="address2"></td>
</tr>
<tr>
<th><label for="zip">* zip</label></th>
<td><input type="text" name="zip" class="al_required"></td>
</tr>
<tr>
<th><label for="city">* city</label></th>
<td><input type="text" class="al_required" name="city"></td>
</tr>
<tr>
<th><label for="state">* state</label></th>
<td>
<select name="state" class="al_required">
<option value="">Select a State</option>
</select>
</td>
</tr>
<tr>
<th><label for="country">* country</label></th>
<td>
<select name="country" class="al_required">
<option value="US">United States</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" class="al_buttons">
<button type="reset">CANCEL</button>
<button type="submit" class="last">ADD</button>
</td>
</tr>
</table>
</form>
<script type="text/javascript" charset="utf-8">
$('#al_address form').validate({
rules: {
name: 'required', first_name: 'required', last_name: 'required', address1: 'required', zip: 'required', city: 'required', state: 'required', country: 'required'
},
messages: {
name: '- Required fields were left blank.'
}
});
</script>
As it stands, this will show the proper message for name
but nothing else. Is it possible with jQuery.validate to just set the 'required' rule on a class, and use that class reference in messages
to display a uniform message for required fields in the form?
The plug in provides a method for this, see the documentation for this. Then you could do:
$(".myClass").rules("add", {
required:true
});
Find more moethods and options here.
you can add class="required" for each control to get required field validation ie
<tr>
<th><label for="name">* address name</label></th>
<td><input type="text" class="required" name="name"></td>
</tr>
<script type="text/javascript" charset="utf-8">
$('#al_address form').validate({
});
</script>
精彩评论