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 '

This email address is already registered.

'; } 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
});
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


  • 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 ‘

  • donny

    Hi,

    I got some crazy trouble, because i can’t get value from input, when i typed this on browser console it’s absolutly works 100%
    [console]
    $(“form#registration input[name=email]”).val();

    [/console]

    but when i implmented with JQuery Validation, i didn’t works.

    this is my code

    [code]

    rules: {
    email: {
    required: true,
    minlength: 3,
    maxlength: 100,
    email: true,
    remote: {
    url: “”,
    type: “post”,
    data: {
    ’email': $(“form#registration input[name=email]”).val(),
    ‘second': ‘aw’,
    ‘config->item(‘csrf_token_name’); ?>': ‘security->get_csrf_hash(); ?>’,
    },
    success: function(e){
    console.log(e);
    },
    error: function(e){
    console.log(e);
    }
    }
    },
    },

    [/code]

    backend

    [code]

    if(!$this->input->is_ajax_request()){

    redirect(‘signup’);

    }else{

    if($this->input->post(’email’)){
    $email = $this->input->post(’email’);
    //check valid email
    $this->load->helper(’email’);

    if(valid_email($email)){
    $this->db->select(‘id’);
    $q = $this->db->get_where(‘users’, array(’email’=>$email));
    if($q->num_rows()>0){
    echo “false”;
    }else{
    echo “true”;
    }
    }else{
    echo “false”;
    }
    }else{
    echo json_encode($this->input->post());
    }
    }

    [/code]

    and i ran the program with the result (browser console) :
    Object {email: “”, second: “aw”}

    it’s null (email)

    Thanks!

    Nice Article Man

  • mpkumar

    Hi,
    I need to check email exist on remote call only on ‘onblur’ event. But now, for character have call ajax request. Below is my code,

    email: {
    validators: {
    notEmpty: {
    message: ‘Email is required’
    },
    emailAddress: {
    message: ‘The input is not a valid email address’
    },
    remote: {
    url: “/users/check_email_exists”,
    type: ‘POST’,
    data: function(validator) {
    return {
    email: validator.getFieldElements(’email’).val()
    };
    },
    message: ‘The email is not available’
    }
    }
    }

  • Silvio Alejandrõ

    Thank you SO much for the ‘Stopping remote validation as you type’ section ☺

  • johndubya

    Sam, have you ever run into a situation where you wanted the form to be invalid until the remote validation is performed? Right now, a user can enter an existing email address and quickly hit the submit button, and the form will go through, since the remote validation had not come back as invalid yet. Have you run into this or, even better, found a solution?

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.