Simplehost Web Hosting

Quick and easy form validation with JavaScript

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.

.

Recent News
Feb 13, 2016

We have deployed PHP 7.0 to selected servers which has up to 4x performance gain on previous versions as well as the most comprehensive language API available. Read More


Feb 08, 2015

Bitcoin payments are now accepted for all hosting products. Bitcoin payments are simple, fast and simple to do on a mobile device. Get your digital wallet today and pay with Bitcoin. Read More