My Ajax Form Validation
December 30th, 2007 in scripts | 9 Comments
I’ve finally written up an extensible script to validate forms server-side using the technique from this article. You can download it or view the demo.
Examples
My method is a little more involved because it accounts for non-javascript users. To make sure it works for them, you’ve got to include a few lines at the top of your form page:
session_start(); $_SESSION['referer'] = $_SERVER['PHP_SELF'];
Next, in the head, you’ve got to include MooTools and the js file:
<script type="text/javascript" src="mootools-beta-1.2b1.js"></script> <script type="text/javascript" src="validator.js"></script>
Then instantiate the class, passing in the id of the form:
window.addEvent('load', function() { new Validator('frm'); });
Here’s how the form should look if you want it usable by non-js users:
<form id="frm" action="process_form.php" method="post"> <label for="f1">Your Name:</label><input type="text" name="f1:required|alpha" id="f1" value="<?php echo $_SESSION['validator']['f1']; ?>" /><?php echo $_SESSION['validator']['f1_error']; ?> <input type="submit" value="Submit!" /> </form>
Notice the name attribute for the input field. The syntax is name:rule1|rule2|rule.... The rules correspond with validation rules defined in the PHP Validator class. You also have to echo some session variables for non-js users. Note that the name and id have to be the same. The minlength, maxlength, differ, and confirm rules have a slightly different syntax. Here are a few examples of those:
<form>
<input type="text" name="f1:minlength{2}|maxlength{10}" id="f1" />
<input type="text" name="f2:differ{f1}" id="f2" />
<input type="text" name="f3:confirm{f3/Name_you_want_to_appear_in_error_text}" id="f3" />
</form>Now let’s take a look at a sample PHP page:
require_once('validator.php'); $myValidator = new Validator($_POST); $myValidator->register(array('mine_custom_rule' => array('/^\d{5}(-\d{4})?$/', "The error message."))); $data = $myValidator->validate(); // do stuff with the data
When instantiating the PHP validator class, you have to pass in the form data. You can also see how to define your own validation rule. Calling validate() will validate the data and return it with cleaned names. If validation fails, the script will die and provide feedback to the user.
The javascript class contains hooks so you can easily change the way errors are displayed. When you instantiate the class, just pass in an object with the events you want to overwrite. Events include onValidate, onInvalidate, onError, onLoading, and onLoaded. To get a list of validation rules, just take a look at the PHP class.
I’ll write up proper documentation soon.

Hi, I'm Chris, a passionate freelance web developer. My languages of choice are PHP and JavaScript, and that's what you'll mostly find in my blog. You'll also find updates about 