这可能对你有用。链接到 jsfiddle
HTML
<form id="commentForm" method="post" action="index.php" style="font-family: Georgia">
<fieldset>
<legend>The main form</legend>
<label for="text1">Text 1</label>
<input type="text" id="text1" name="text1" />
<br /><br />
<fieldset id="opt">
<legend>This section is only rquired when "Add" button is clicked</legend>
<label for="text2">Text 2</label>
<input type="text" id="text2" name="text2" />
<br /><br />
<button id="add">Add</button>
</fieldset>
<br />
<label for="text4">Text 4</label>
<input type="text" id="text4" name="text4" />
<br /><br />
<input type="submit" id="submit" value="Post Main Form" />
</fieldset>
</form>
JavaScript
$('#commentForm').validate({
//ignore everything in the sub-form
ignore: '#opt *',
rules: {
text1: {
required: true,
minlength: 2
},
text4: {
required: true,
minlength: 2
}
}
});
$('#add').click(function () {
var txt = $('#text2');
//here you add validation rules for sub-form elements
txt.rules('add', {
required: true
});
//here you trigger the validation for elements in subform
txt.valid();
/* here you do your ajax stuff */
return false;
});
这种方法 jQuery 验证器插件的ignore
选项以及.valid()
手动触发元素验证的方法。我希望它有所帮助。
此示例已使用jQuery Validation Plugin - v1.10.0