I used jquery validation (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) for form validation. The followings are some fragments of my code:
HTML:
<Summing up, in order to employ both form validation and ajax submission, add 'submitHandler' to the validate() function:
$("#formID").validate({
onkeyup:false,
rules: {
...
},
messages: {
...
},
// Submit the form
submitHandler: function(form) {
theUrl = '/processData';
var params = $(form).serialize();
$.ajax ({
type: "POST",
url: theUrl,
data: params,
processData: false,
async: false,
success: function(returnData) {
$('#content').html(returnData);
}
});
}
});
I had the same problem, what I did is:
1) change the the submit button :
from :
<input type="submit" class="savebutton" id="save" value="Save" />
to
<input type="button" class="savebutton" id="save" value="Save" />
(the save button is not going to submit the form when is click it).
2)change my validation script to:
<script type="text/javascript">
$(document).ready(function() {
$('#form').validate({
rules: {
qty: {
max: 100,
required: true
}
},
messages: {
qty: "please check quantity",
}
});
$( "#save" ).click(function() {
if ($('#form').validate())$('#form').submit();
});
});
</script>
when the "save" button is hit, it validates the form. if the validation is correct, then it's going to submit the form.
Instead of:
// Submit the form by Ajax
$(document).ready(function() {
$('.formID').ajaxForm({
success: function(returnData) {
$('#content').html(returnData);
}
});
});
Use the submitHandler
option of the Validate plugin, like this:
$("#formID").validate({
//all your other options
submitHandler: function(form) {
$(form).ajaxForm({
success: function(returnData) {
$('#content').html(returnData);
}
});
}
});