AJAX Form Validation
A conversation I have had on more than one occasion revolves around form validation. Client side or server side? I think we all know that the answer is, and always has been: BOTH. That being said, AJAX provides a delightful way to accomplish both tasks at once.
Using AJAX, we can actively examine the users input as they are typing - and help them get to end result we are looking for. Below, you will find a very basic example I mocked up to demonstrate what I am talking about. As you start typing your email address into the form field - we are sending AJAX requests to a PHP script which is running a quick regular expression check to make sure the email address is valid. In reality, in order to make this worthwhile, the AJAX call would need to be doing something slightly more useful - like verifying that the email address has not already been registered. This PHP script sends a response back, and using some basic dHTML - give the user an alert (although in this case a rather rude one). The other thing we are doing here, is unlocking the ability to ‘Submit’ the form - once our criteria has been met. You will see that the Submit button is disabled until we get a valid email address.
Example: AJAX Email Validation Enter email below.
Now, this is admittedly a very simple example - but I think it serves to demonstrate a very useful, and quite practical technique. Some other common uses for this type of AJAX validation are:
- Checking for available usernames against an existing database
- Suggesting alternative available usernames based on previously entered data
- Examining password strength
- Populating extra form fields (city, state, country) once a user enters a zip-code
This method delivers the best of both worlds as far as validation is concerned. It provides the immediacy that Javascript has previously delivered, but also the security of server-side validation. Keep in mind, that if the user has disabled Javascript - this method also will not work - so make sure to use the same server side validation functions when the form is actually submitted.