My Ajax Form Validation

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.

9 Responses to “My Ajax Form Validation”

  1. Matt

    Hi There

    The link to the downloadable scripts doesnt work. Please fix as I have been looking for a well written validator for some time.

    Matt

  2. Chris

    Sorry about that. The link is fixed now.

  3. Fabian

    Bro this looks neet but I can“t make it work, can you put a full working example to download.

    Thanks in advance

  4. Chris

    Fabian, it’s a lot more powerful and well documented now. You can see the update here: http://www.chromasynthetic.com/blog/archive/126

  5. Ayaz

    Hi,

    I have tried this validator, it works great. My only problem is that i want to redirect the user to a thank you page when the form is submitted succesfull. How can i achieve this. I know i should use the _ajax argument, but how.

  6. Chris

    Ayaz, for JavaScript users, you’ll have to use window.location when a successful response is returned. For non-js users, you’ll have to do it in php using header("Location: http://www.url.com“). Let me know if I’ve explained things clearly enough.

  7. Ayaz

    Hi Chris,

    I am not 100 sure how to use the _ajax argument. Should i put this in the form or the php file that validates the posted info.

  8. Ayaz

    Another question, i tried to validate a radio button like this , but that doesn’t work. And checkbox doesn’t work either.
    Please help.

  9. Chris

    Ayaz,

    You don’t have to do anything with the _ajax argument. In your javascript when you instantiate a new instance of ValerieClient, pass in an onFormValidate function that redirects the user using the method I already described.

    Currently, checkboxes and radio buttons can’t be validated. I thought I tried it though and it worked, but that may be with the version in trunk.