jQuery:如何在ajaxForm函数中包括验证? [英] jQuery: how to include validation in the ajaxForm function?
问题描述
此问题已被提出,但答案不是尚未确认.我试过了,但是没有用.所以我想再次问同样的问题(这合适吗?如果不合适,请告诉我该怎么做).
This question has been asked, but the answer wasn't confirmed. I tried it but it didn't work. So I would like to ask the same question again (Is this appropriate? If not, please advise me what to do).
我有一个需要验证的表单,然后使用ajaxForm提交(该表单包含图像和文件数据,因此使用.serialize()
提交将不起作用).详细信息如下:
I have a form which needs to be validates and then submitted with ajaxForm (the form contains image and file data, so submission with .serialize()
won't work). The following are the details:
HTML:
<form id="myForm" action="..." method="post" enctype="multipart/form-data">
...
<input type="file" name="image" /><br />
<input type="file" name="file" /><br />
...
</form>
jQuery:
$(document).ready(function() {
$("#myForm").ajaxForm ({
beforeSubmit: function() {
$("#myForm").validate({
onkeyup:false,
rules: {
...
},
messages: {
...
},
});
},
success: function(returnData) {
$('#content').html(returnData);
}
});
});
ajaxForm
部分正常.但是,该表单只是未经验证而提交.
The ajaxForm
part is OK. But the form is simply submitted without validation.
推荐答案
.validate()
是用于在DOM ready上初始化插件,因此请将该插件移出其他函数.
.validate()
is used for initializing the plugin on DOM ready, so pull that outside of the other function.
初始化 DOM中的两个插件,然后利用任何适当的内置回调函数...
Initialize the two plugins within DOM ready, and then utilize any appropriate built-in callback functions...
- 使用
ajaxForm
插件的beforeSubmit
回调函数使用验证插件的.valid()
方法以编程方式检查表单的有效性.
- Use the
beforeSubmit
callback function of theajaxForm
plugin to programmatically check the form's validity using the Validate plugin's.valid()
method.
您无需担心创建任何新的submit
处理程序或click
处理程序功能,因为两个插件都已经自动捕获了submit
事件.
You will not need to worry about creating any new submit
handler or click
handler functions since both plugins already capture the submit
event automatically.
工作示例: http://jsfiddle.net/MF26D/
Working DEMO: http://jsfiddle.net/MF26D/
将您的代码重新排列为如下所示:
Rearrange your code into something more like this:
$(document).ready(function () {
$("#myForm").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
//...
},
messages: {
//...
}
});
$("#myForm").ajaxForm({ // initialize the plugin
// any other options,
beforeSubmit: function () {
return $("#myForm").valid(); // TRUE when form is valid, FALSE will cancel submit
},
success: function (returnData) {
$('#content').html(returnData);
}
});
});
这篇关于jQuery:如何在ajaxForm函数中包括验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!