I’m sure you’ve seen those nice interactive form validations on some Web 2.0 websites. The validation occurs while you’re typing your form input. For example, you’re typing your email in the email address field. You see a red “X” mark beside the field and when you’re finished typing your email address, a green check mark replaces the red “X” mark. What happens there is while you’re typing in your email address, the page communicates with the server to validate what you’re typing. When you finished typing your email address and the data you keyed in is valid, it passes the validation so it shows the green check mark without reloading the page. This is done using Ajax.

In this tutorial, you’re going to learn how to make this kind of interactive, Ajax-powered form validation (the same validation sample mentioned earlier). If you haven’t used Ajax before, don’t worry because I will show you how you can create Ajax-powered applications without worrying about the whole XmlHttpRequest process. If you can program with PHP and a little Javascript, you’re good to go. All you need is this handy little open-source Ajax toolkit called Sajax.

So the first thing you need to do is download the Sajax toolkit. Unzip the archive file and find the file named “Sajax.php”, since we’ll be using it in a PHP application. It is located under a folder named “php”. Inside that folder, you’ll also find some code samples. Sajax supports other server-side scripting languages as well like ASP, Perl, Python, and others. Upload the “Sajax.php” file into your webserver in a directory accessible by the PHP form validation script that you’re going to make. The sample code below show’s the implementation of an email validation script using PHP, Javascript, and Sajax. Examine the script to see how it works. I placed lots of comments to help you out.

<?php

# Include the Sajax toolkit
require("Sajax.php");

# Define the email validation function
function validate($email) {
    if (preg_match(
    '/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*@[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/',
    $email)) {
        return 'Valid';
    } else {
        return 'Invalid';
    }
}

# Initialize Sajax
sajax_init();
# Export the server-side function to Sajax
sajax_export('validate');
# Handle client request
sajax_handle_client_request();

?>

<html>
<head>
    <script type="text/javascript">
    <?php
        # Sajax toolkit generated javascript code
        sajax_show_javascript();
    ?>
    // Sends the email input to the server-side function
    // and throws the return value to showValidation.
    function js_validate(email) {
        x_validate(email, showValidation);
    }
    // Prints the return value on the screen.
    // Changes the container's font color to green
    // if the return value is "Valid" and
    // to red if not.
    function showValidation(html) {
        var element = document.getElementById('validation');
        element.innerHTML = html;
        if (html=='Valid')
            element.style.color = 'green';
        else
            element.style.color = 'red';
    }
    </script>
</head>
<body>
    <form>
    Email: 
    <input type="text" 
    onkeyup="js_validate(this.value)" name="email" /> 
    <span style="font-weight:bold;" id="validation"></span>
    </form>
</body>
</html>
  1. Imports the Sajax toolkit.
  2. Defines the function that will validate the email address input by the user.
  3. The next 3 lines, to summarize, exports the server-side function so it can be called through Javascript.
  4. The next lines display the HTML web page.
  5. Inside the header and script tags, you’ll find the call to sajax_show_javascript. This outputs all the Javascript code necessary to utilize the server-side function.
  6. The Javascript function js_validate sends the email input to the server side function, catches the return value and throws it to the other Javascript function – showValidation. Within this function definition, you’ll notice the call to a function “x_validate”. This Javascript function is generated by Sajax. It calls the server-side function “validate” and passes the parameter, “email”. The last parameter of x_validate is the name of the function that will receive the return value of the server-side function. When you call a server-side function using Javascript and Sajax, you simply add a prefix “x_” to the function name. The parameters are the same as the server-side function but you need to add one parameter at the end. This is the name of the Javascript function that will receive the return value. If this parameter is left out, no return values will be handled.
  7. The Javascript function showValidation simply puts this return value (“Valid” or “Invalid”) in the container “validation”. Also, if the return value is “Valid”, this function changes the font color of the container to green. Otherwise, it sets the font color to red.
  8. The function js_validate is called every time the user types something in the input field (onkeyup event).

We didn’t do the little red “X” and green check marks here but with just a little creativity, you should be able to implement this.

Tags :

8 Responses to “How to Create Interactive Form Validation Using Ajax”


  1. Nate

    Said on May 21, 2008 :

    Client-side validation while you type is rarely done using AJAX. AJAX checks are usually onblur or onsubmit. Checking after every key up will create a lot of response noise that is outdated before it is received.

    A lot of client-side validation can fit into a regex, such as the posted example, and can be rewritten to run only on the client.

  2. Darren

    Said on May 22, 2008 :

    @Nate

    I agree that you can implement this example without using Ajax. But this article isn’t just talking about that one example. The example I did here was just to serve as an example. I made it really simple so it will be much easier to explain and understand.

    But what about checks that require database queries? For example, verify if a username that was input is available, or an email address is already registered? In such cases, you can use what was mentioned in this tutorial. Only the script will be a bit more complex with SQL queries added.

  3. Nate

    Said on May 23, 2008 :

    I agree that there are plenty of situations where ajax validation can be extremely useful, I just didn’t see it being useful in the example given. I understand the need to keep it simple though.

    The onkeyup thing is never really a good idea for anything related to ajax, unless you build a delay check into the onkeyup event before triggering the ajax event. It just creates a lot of unneeded requests, and if you extend the example to a database lookup you will be hitting the database a lot more than needed.

  4. Darren

    Said on May 27, 2008 :

    If I used “onblur” in my example instead of “onkeyup”, there wouldn’t be any discussions here. I’m kinda glad I used “onkeyup”. ;)

    If you read the post (and not just the code sample) you’ll know the focus of this post is Sajax.

    Well you’re right, If I was doing the database query example I wouldn’t do it that way either. I’ll probably make an index for the lookup. But if I mention all of that in detail then 1 article wouldn’t be enough or the focus will be all over the place.

  5. aphrodite

    Said on July 25, 2008 :

    Hi! I tried out this code, its great but I was wondering if you could explain how to apply this to multiple fields. When I tired to apply to multiple fields it dont give me the output I want. Im new to php and javascript, so maybe my logic is wrong. Please help. The code I used is as follows:

    function js_validate(eadd) {
    x_validate(eadd, showValidation);
    }
    function showValidation(html) {
    var element = document.getElementById(‘validation’);
    element.innerHTML = html;

    if (html==’Valid’)
    element.style.color = ‘green';
    else
    element.style.color = ‘red';
    }

    function njs_validate(name) {
    x_validate(name, nshowValidation);
    }
    function nshowValidation(html) {
    var nelement = document.getElementById(‘name’);
    nelement.innerHTML = html;

    if (html==’Valid’)
    nelement.style.color = ‘green';
    else
    nelement.style.color = ‘red';
    }

     
    Name

     
    Eg: –  First Name Surname

     
    E – mail address

    thanx!

  6. varun jain

    Said on May 13, 2010 :

    even i want it for multiple fields
    like say registration form

  7. David

    Said on November 22, 2010 :

    Here is a demonstration applying this to multiple objects. Enjoy.

    // Sends the email input to the server-side function
    // and throws the return value to showValidation.
    function js_validate_email(email) {
    x_validate_email(email, showValidationEmail);
    }
    function js_validate_phone(phone) {
    x_validate_phone(phone, showValidationPhone);
    }

    // Prints the return value on the screen.
    // Changes the container’s font color to green
    // if the return value is “Valid” and
    // to red if not.
    function showValidationEmail(html) {
    var element = document.getElementById(‘vemail’);
    element.innerHTML = html;
    if (html==’Valid’)
    element.style.color = ‘green';
    else
    element.style.color = ‘red';
    }
    function showValidationPhone(html) {
    var element = document.getElementById(‘vphone’);
    element.innerHTML = html;
    if (html==’Valid’)
    element.style.color = ‘green';
    else
    element.style.color = ‘red';
    }

    Email:

    Phone:

  8. David

    Said on November 22, 2010 :

    Hmm… looks like the format got murdered by the forum. Sorry guys.

Post a Comment