Ajax Form Validation Technique

I think the most important aspects of building and processing a form is how you validate data, help the visitor with tips, how you make it easy to understand what’s required and optional and how it performs after hitting the submit button. What do I mean by how it performs? Well, let’s suppose you have a huge form in front of you (try opening an account on a dating site for example – the whole process of 3+ pages is full of forms)…
you complete all of them and you hit submit. You didn’t knew that free email accounts such as yahoo, hotmail or google are not allowed because the webmaster forgot to mention or you simply didn’t noticed the small size 1 font telling you that. The page takes your data, goes to the next page which validates it and returns: “Hey man! I told you not to use free email accounts!”. This is ok and we’re used to it but imagine this horrible scenario that is present on thousands of websites: you’re supposed to fill the whole form all over again because it didn’t remembered your data.
What will you do? I’ll tell you what: what 80% will do is leave unless they need that membership. Now we change roles and think of it as if we were the webmaster of that website. Wow! That’s a lot of people leaving just because of this process. There are a lot of mistakes that webmasters do (during form processing and validation in our case) and they don’t know about because they’re not informed well enough.

We are going to learn from this tutorial how to create a form that will process using AJAX and PHP. Based on mootools as a javascript library and for the AJAX effect, our form will call the php page in order to process and validate our inputs. From here the title which represents the whole above definition: AJAX form validation.

Our example is supposed to be a registration page. It will do nothing after validation but show errors or a success message. If you wish to combine it and really create a registration page with email activation, membership, login page, forgot password, mysql tables and all that stuff please read the PHP login tutorial as well.

The form will be a simple one pointing to register.php in our case without redirecting or refreshing the page on submit thanks to mootools and will use a div (<div id=”log”>) to communicate with the visitor by showing error or success messages upon validation. Thanks to Fx.Styles we’re able to display a loading spinner by modifying the css property of our div until we receive a response from the php page (register) which is supposed to take care of the validation.

window.addEvent('domready', function(){
	$('registerForm').addEvent('submit', function(e) {
	    new Event(e).stop();
	    var log = $('log_res').empty().addClass('ajax-loading');
	    this.send({
	        update: log,
	        onComplete: function() {
	            log.removeClass('ajax-loading');
	        }
	    });
	});
});

Looking at the Javascript code above you will notice a very important thing that we can use with mootools. The domready event which is way more faster than the old window onload. The form is ready to validate using AJAX in no time and all that I’ve mentioned above sits on a 23kb js file. That’s a great tool to play with if you ask me.

Let’s move to the php file where the main “engine” sits. Our validation will be simple, we will check if the required data (all of them are required in our case) is not empty, if the two passwords match one another and if the visitor provided a valid email address.

<?php
	include('functions.php');

	if ($_POST['First_name']=='' || strlen($_POST['First_name'])<3)
	{
		$errors[] = 'First name is required and must contain 3 characters or more';
	}

	if ($_POST['Last_name']=='' || strlen($_POST['Last_name'])<3)
	{
		$errors[] = 'Last name is required and must contain 3 characters or more';
	}

	if ($_POST['Username']=='' || alpha_numeric($_POST['Username'])==FALSE)
	{
		$errors[] = 'Username is required and must be alpha-numeric';
	}

	if ($_POST['Password']=='' || alpha_numeric($_POST['Password'])==FALSE)
	{
		$errors[] = 'A password is required and must be alpha-numeric';
	}

	if ($_POST['Password']!=$_POST['re_Password'])
	{
		$errors[] = 'The two passwords must match';
	}

	if (valid_email($_POST['Email'])==FALSE)
	{
		$errors[] = 'Please supply a valid email address';
	}

	if(is_array($errors))
	{
		echo '<p class="error"><b>The following errors occured</b></p>';
		while (list($key,$value) = each($errors))
		{

			echo '<span class="error">'.$value.'</span><br />';
		}
	}
	else {
		//do something here----store to db, send email
		echo '<p><b>Success!</b></p>';
		echo '<span>Your registration was successfully processed. You may login and start using your account. Thank you for registering !</span>';
	}

?>

This is pretty usual and easy even for real beginners. The important thing in our validation process is how we build and display the error messages. Using if, elseif and else you’re able to achieve something similar only that (in case we have more than 1 error) the messages will be displayed one at a time. As you can see, I’ve used only if statements and each time one of them finds a mismatch or an error adds a value to the array $errors[].

The last statement checks if we have an array (since the array $errors[] can be defined only if we have an error). In case the result is yes, we perform a loop to display all of them on different lines:

while (list($key,$value) = each($errors))
{
	echo '<span class="error">'.$value.'</span><br />';
}

In case not, there’s no need for a loop since we can show a success message in only one case (if everything passed our ajax validation). I’ve added a comment there (//do something here—-store to db, send email), it’s the place where you should place your code for storing the info to the database, sending confirmation emails etc.

Here’s a demo of our application at work (download link lower on the page). Enjoy!

Leave a Comment!