我正在创建一个Web应用程序,其中包含用户提交给服务器的一种大型表单。
这种形式具有标准的jQuery验证,效果很好。 (http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
但是,表单中间的A节将需要通过ajax调用提交。可以说表单的此部分有一个简单的“添加”按钮-按下添加按钮时,是否可以仅验证表单的此部分?
并在正常提交时验证表格的其余部分。我看过jQuery Validation API,什么也看不到。
我以为可以打电话给我:
$('#commentForm').validate({
rules : {
cname: {
required: true,
minlength: 2
}
}
}).element("#cname");
不幸的是,这增加了按下主提交按钮时会检查的验证。
在此问题上的任何帮助或建议,将不胜感激:)
最佳答案
这可能对您有用。 Link to 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
进行了测试关于jquery - 大型jQuery验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16251787/