是否可以使用jQuery.validate验证表单中的整个元素类?我知道您可以按名称为元素分配规则,但是您也可以按类选择这些元素吗?我的网站上有一个表单,除了required
规则之外不需要任何其他内容,而且每个字段都需要键入一些笨拙,特别是在处理messages
对象时!
这是我的代码:
<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>
就目前而言,这将显示name
的正确信息,但没有其他信息。是否可以使用jQuery.validate在类上设置“required”规则,并在messages
中使用该类引用来显示表单中必填字段的统一消息?
答案 0 :(得分:2)
插件提供了一种方法,请参阅documentation for this。然后你可以这样做:
$(".myClass").rules("add", {
required:true
});
查找更多moethods和选项here。
答案 1 :(得分:1)
您可以为每个控件添加 class =“required”以获得必要的字段验证,即
<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>