Adding reCaptcha validator to jQuery Validate with AJAX check and PHP

Here we will see how to integrate reCaptcha 1.0 with the famous jQuery Validate plugin. I assume that you already have a reCaptcha account (otherwise read the Step 1 from this post) because you will need a public and private key related to your site.

HTML

1. Load the reCaptcha AJAX js:

<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>

2. Place this div where you want to display the reCaptcha form.

<div id="captcha"></div>

Javascript (or Coffeescript)

// Displays the recpatcha form in the element with id "captcha"
Recaptcha.create("your_public_key", "captcha", {
  theme: "clean",
  callback: Recaptcha.focus_response_field
});

// Add reCaptcha validator to form validation
jQuery.validator.addMethod("checkCaptcha", (function() {
  var isCaptchaValid;
  isCaptchaValid = false;
  $.ajax({
    url: "libs/checkCaptcha.php",
    type: "POST",
    async: false,
    data: {
      recaptcha_challenge_field: Recaptcha.get_challenge(),
      recaptcha_response_field: Recaptcha.get_response()
    },
    success: function(resp) {
      if (resp === "true") {
        isCaptchaValid = true;
      } else {
        Recaptcha.reload();
      }
    }
  });
  return isCaptchaValid;
}), "");

// Validation
$("form").validate({
  rules: {
    // your rules here...

    // Add a rule for the reCaptcha field
    recaptcha_response_field: {
      required: true,
      checkCaptcha: true
    }
  },
  messages: {
    recaptcha_response_field: {
      checkCaptcha: "Your Captcha response was incorrect. Please try again."
    }
  },
  onkeyup: false,
  onfocusout: false,
  onclick: false
});
  #
  # * Recaptcha
  # 

  # Displays the recpatcha form in the element with id "captcha"
  Recaptcha.create "your_public_key", "captcha",
    theme: "clean"
    callback: Recaptcha.focus_response_field

  # Add reCaptcha validator to form validation
  jQuery.validator.addMethod "checkCaptcha", (->
    isCaptchaValid = false
    $.ajax(
      url: "libs/checkCaptcha.php"
      type: "POST"
      async: false
      data:
        recaptcha_challenge_field: Recaptcha.get_challenge()
        recaptcha_response_field: Recaptcha.get_response()

      success: (resp) ->
        if resp is "true"
          isCaptchaValid = true
        else
          Recaptcha.reload()
    )
    return isCaptchaValid
  ), ""

  # Validation
  $("form").validate
    rules:
      // your rules here...

      // Add a rule for the reCaptcha field
      recaptcha_response_field:
        required: true
        checkCaptcha: true

    messages:
      recaptcha_response_field:
        checkCaptcha: "Your Captcha response was incorrect. Please try again."

    onkeyup: false
    onfocusout: false
    onclick: false 

PHP

  1. Download the reCaptcha PHP library and extract the zip into a folder in your web project (in my example in /libs)
  2. Create a file called checkCaptcha.php, this script will validates the captcha code:
// Include the reCaptcha library
require_once __DIR__ . "/libs/recaptcha-php/recaptchalib.php";

$privatekey = "your_private_key";

// reCaptcha looks for the POST to confirm
$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

// If the entered code is correct it returns true (or false)
if ($resp->is_valid) {
  echo "true";
} else {
  echo "false";
}

Extra: CSS/LESS

You could experience some issues that you solve with this CSS:

/*
 * reCaptcha override fixes
 */
// Avoid to hide the bottom border of the image
.recaptchatable #recaptcha_image{
  overflow:hidden;
}

// Remove the blank space at the bottom of the page generated by the iframe
body > iframe[src='about:blank'] {display:none !important;}
header iframe,
section iframe,
footer iframe,
div iframe { display:inline; }
  • Khuong Vu

    Thank you for your post. Your tutorial works. (For people new to Ajax and JavaScript like me, it is a bit difficult to work with the languages. The scripting languages, Ajax and JavaScript, don’t throw an error, and so I thought I put in some echo statements to diagnose the problems. As it turns out the echo statements are not good diagnostic tools, because they can be used to return values. Anyway, I was just having problems with “require_once” and the “echo” statements. Otherwise, the tutorial works “as is”.)

  • Jordan

    How can this code be adapted to use the new reCaptcha API? Thanks!

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo