I used jquery validation (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) for form validation. The followings are some fragments of my code:
HTML:
<form id="formID" action="/processForm" method="post">
...
<input id="name" type="text" name="name" size="10" />
<input id="username" type="text" name="username" size="10" />
...
<input type="submit" value="Submit" />
jQuery:
$("#formID").validate({
onkeyup:false,
rules: {
name: {required: true},
username: {required: true, checkUsername: true}
...
},
messages: {
name: {required: "Must fill"},
username: {required: "Must fill", checkUsername: "Username unavailable"},
...
}
});
// Check if username exists
$.validator.addMethod('checkUsername', function(username) {
var postURL = "/checkUsername";
$.ajax({
...
});
return ...;
}, '');
// Submit the form by Ajax
$(document).ready(function() {
$('.formID').ajaxForm({
success: function(returnData) {
$('#content').html(returnData);
}
});
});
Something odd is that I can leave some of the required fields blank or unchecked, and the form can still be submitted. Some required fields can prevent from submitting if left blank, but others don’t. Did anybody encounter the same strange problem? Or did I do anything wrong here?
BTW, if I click the submit button without filling anything, all required fields show error messages correctly. But some of them just won’t prevent the form from been submitted. Please help.
EDIT:
The Ajax form submission function at the bottom doesn’t seem to work. How do I correct it?
Summing up, in order to employ both form validation and ajax submission, add ‘submitHandler’ to the validate() function: