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).
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);
}
});
});
The ajaxForm
part is OK. But the form is simply submitted without validation.
.validate()
is used for initializing the plugin on DOM ready, so pull that outside of the other function.
Initialize the two plugins within DOM ready, and then utilize any appropriate built-in callback functions...
- Use the
beforeSubmit
callback function of theajaxForm
plugin to programmatically check the form's validity using the Validate plugin's.valid()
method.
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.
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);
}
});
});
try this
$(document).ready(function() {
$("#myForm").ajaxForm ({
beforeSubmit: function() {
if (!$("#myform").valid())
return;
},
success: function(returnData) {
$('#content').html(returnData);
}
});
});
Can call the form plugin within a submit handler:
$("#myForm").submit(function(e){
e.preventaDefault();
var isValid=/* run your validation code that determines true or false*/
if( isValid){
$(this).ajaxForm({/* plugin options*/})
}
})
来源:https://stackoverflow.com/questions/15322284/jquery-how-to-include-validation-in-the-ajaxform-function