jQuery Ajax Validation Use the Remote Rule

Sam Deering
Tweet

I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used to make an ajax request instead of specifying a custom rule which has an ajax call it in. This will save you heaps of time with those custom validation rules. Basic jQuery Form Validation Tutorial (2mins).


Example: Checking if a users email is already registered.

The new remote method way

As you can see to pass through data you can simply use the key pair syntax so the request sent below the data is “&emails=email@jquery4u.com”. The return values for your backend script is either json encoded true for a validation pass or html msg for validation fail.

//VALIDATE USER EMAIL
$(':input[name="uAcc"]').rules("add",
{
  "remote" :
  {
      url: 'validateEmail.php',
      type: "post",
      data:
      {
          emails: function()
          {
              return $('#register-form :input[name="email"]').val();
          }
      }
  }
});

The old add custom method way

//VALIDATE USER EMAIL
$.validator.addMethod("validateUserEmail", function(value, element)
{
    var inputElem = $('#register-form :input[name="email"]'),
        data = { "emails" : inputElem.val() },
        eReport = ''; //error report

    $.ajax(
    {
        type: "POST",
        url: validateEmail.php,
        dataType: "json",
        data: data,
        success: function(data)
        {
            if (data !== 'true')
            {
              return '<p>This email address is already registered.</p>';
            }
            else
            {
               return true;
            }
        },
        error: function(xhr, textStatus, errorThrown)
        {
            alert('ajax loading error... ... '+url + query);
            return false;
        }
    });

}, '');

$(':input[name="email"]').rules("add", { "validateUserEmail" : true} );

Backend PHP Script

< ?php

/* check if email is already registered */

//connect to db using mysqli

if (!empty($_POST['email']))
{
    $email = $mysqli->real_escape_string($_POST['email']);
    $query = "SELECT ID FROM users WHERE user_email = '{$email}' LIMIT 1;";
    $results = $mysqli->query($query);
    if($results->num_rows == 0)
    {
        echo "true";  //good to register
    }
    else
    {
        echo "false"; //already registered
    }
}
else
{
    echo "false"; //invalid post var
}

?>

Another Example to help

/* register script */

(function($,W,D,undefined)
{
    $(D).ready(function()
    {

         //form validation rules
         $("#register-form").validate({
             rules:
             {
                email:
                {
                    required: true,
                    email: true,
                    "remote":
                    {
                      url: 'validateEmail.php',
                      type: "post",
                      data:
                      {
                          email: function()
                          {
                              return $('#register-form :input[name="email"]').val();
                          }
                      }
                    }
                },
                name:
                {
                    required: true,
                    minlength: 3
                },
                password:
                {
                    required: true,
                    minlength: 8
                },
                password_repeat:
                {
                    required: true,
                    equalTo: password,
                    minlength: 8
                }
             },
             messages:
             {
                 email:
                 {
                    required: "Please enter your email address.",
                    email: "Please enter a valid email address.",
                    remote: jQuery.validator.format("{0} is already taken.")
                 },
                 name: "Please enter your name.",
                 password: "Please enter a password.",
                 password_repeat: "Passwords must match."
             },
             submitHandler: function(form)
             {
                form.submit();
             }
         });

    });

})(jQuery, window, document);

Stopping remote validation as you type

By default the validation plugin will send off an ajax request for a remote rule every key you press causing too many ajax requests being sent to validate fields. One way to disable this is to deactivate the onkeyup validation so that the remote rule is only validated via ajax once you have finished typing into the input.

$("#register-form").validate({
   onkeyup: false //turn off auto validate whilst typing
});

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://top10googletrends.com BennyB

    Awesome I never knew about the remote method!
    Thx

    • http://jquery4u.com/ jQuery4u

      Your welcome Benny B

  • David Harkness

    The first example has a missing open quote:

    url: validateEmail.php’,

    should be

    url: ‘validateEmail.php’,

    Thanks for this!

    • http://jquery4u.com/ jQuery4u

      Thanks David, I’ve fixed it up.
      Sam

  • Pingback: 10 Random Ajax and jQuery Plugins | jQuery4u

  • Penay

    Thanks for the article, dude !

    • http://jquery4u.com/ jQuery4u

      Thanks

  • http://www.facebook.com/stephmontreal Steph Moreland

    Is there a way to do this with classic asp in order to verify a reCAPTCHA?

    • http://jquery4u.com/ jQuery4u

      Not sure Steph but would be keen to find out if anyone knows!
      Sam

  • Saad

    How can I show message that this email is available ?????

  • Rubab

    Hi,

    I am using following code. all validation working but form is not submitting when all required fields are correctly entered. when I remove “success” function from remote then its working. Please check where i doing wrong in code.

    remote: {url: “url.php” ,
    type: “get”,
    dataType: ‘json’,
    data: {
    country_code: function() { return $(‘option:selected’, “#country-select”).attr(‘calling_code’); }

    },
    success: function(data){
    if(data){
    jQuery(“#pref_lang”).show();
    }else{
    jQuery(“#pref_lang”).hide();
    }

    }
    }

    • http://jquery4u.com/ jQuery4u

      Hi Rubab,
      Can you try adding an error: function see if it gets fired? What does it say in the network console HXR when it validates. Also what does your backend script return?

  • BevSDC

    Thanks! These were the best jQuery validation remote examples I found.

  • Jaya Dianto

    great code, very awesome ^_^

  • ahmad

    thank you man .. works like a boss .. :)

  • homer

    Hi,

    I created a remove validation and I set the the onkeyup to false such that it only validates once the element is already out of focus say for example I press the tab key. However I noticed that it waits for the ajax call to finish before the cursor jumps to the next element since I pressed tab key. Is there any way to avoid this such that it does not need anymore to wait for the ajax call to finish and immediately the cursor moves to the next element.

    Thanks!

  • homer

    Hi,

    I created a remote validation and I set the the onkeyup to false such that it only validates once the element is already out of focus say for example I press the tab key. However I noticed that it waits for the ajax call to finish before the cursor jumps to the next element since I pressed tab key. Is there any way to avoid this such that it does not need anymore to wait for the ajax call to finish and immediately the cursor moves to the next element.

    Thanks!

  • LS

    Ajax request type “JSON” and you return data with a “echo “true” ” from server response… Why not write rater ‘ type : text ‘