Form validation is a very routine task and having a basic script to cover the simple stuff can be of great benefit. You should always develop strong validation of all inputs on the server side. This example will just show you something to help users save time in forms and check for required fields. The rest of the validation should be implemented in your application models.
First add a hook for form submits.
$(document).ready(function()
{
//Auto validate forms
$('form').bind("submit",validate_form);
});
And the function to validate the required fields.
//Validates required fields on a form
function validate_form()
{
var validation_errors = 0;
$('.required input, .required textarea, .required select',this).each(function(i){
if(this.value == null || this.value == "")
{
validation_errors++;
$(this).addClass("error");
$(this).bind('blur',check_required_field);
}
else
$(this).removeClass("error");
});
return !(validation_errors);
}
And there you have it, quick and easy form validation. You should use CSS to style the inputs with the error class.
.
