HTML.form.guide

Google reCaptcha 2 JavaScript Validation (client side)

Google reCaptcha 2 validations javascript validations

reCaptcha is a great “bot” detection solution from Google. Google watches the pattern of user interaction to decide whether it is a “bot” or a real user. It is near impossible for a “bot” to simulate those patterns. So reCaptcha succeeds in blocking spam most of the time.

Versions of reCaptcha

reCaptcha version 1

reCaptcha version 1 used to show a couple of words in an image and the user had to enter the words in a box to prove they are not “bots”.


image source

reCaptcha version 2

The reCaptcha version 2 is simple and user-friendly. The user is to check a box saying “I am not a robot”. However, sometimes, this version of the captcha also throws some picture puzzles too. It generally depends on how the algorithms of Google feels like the user’s session is. Most of the time, genuine users get to complete the Captcha just by a checkbox.

reCaptcha version 3

Version 3 of reCaptcha is a JavaScript API that returns a score that indicates whether Google thinks this is a “bot” or not. There is no user interaction required.

register with reCaptcha

Go to the reCaptcha site and register for reCaptcha. Remember to enter your domains correct.
recaptcha registration

On completing the form, you will get a site key and a secret key. We will use the site key while displaying the recaptcha (see the code below)

How to disable domain validation temporarily

reCaptcha will insist the page should be from the designated domains only and will throw an error when you load the page from staging server or localhost. You can disable the domain validation temporarily in the settings page of the captcha (press the settings icon and update the setting)
recaptcha settings

reCaptcha HTML code

Here is a simple HTML form page with a form that contains the reCaptcha:

<html>
  <head>
    <title>reCaptcha validation demo</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
<div class="form_container">
  <form action="#" id="my_captcha_form">
    <div class="g-recaptcha" 
data-sitekey="6LfrFKQUAAAAAMzFobDZ7ZWy982lDxeps8cd1I2i" 
></div>
    <p>
    <button type="submit" >Submit</button>
    </p>
  </form>
</div>
</body>
</html>

We included the reCaptcha api.js from the link https://www.google.com/recaptcha/api.js

Then added class=g-recaptcha and data-sitekey to a div attribute.

This will display a captcha when displayed.

reCaptcha Javascript Validation

The HTML code above only displays the Captcha. In order to verify that the user is not a “bot” we have to first verify in the client side and then on the server side.

Here is the client side validation:

document.getElementById("my_captcha_form").addEventListener("submit",function(evt)
  {
  
  var response = grecaptcha.getResponse();
  if(response.length == 0) 
  { 
    //reCaptcha not verified
    alert("please verify you are humann!"); 
    evt.preventDefault();
    return false;
  }
  //captcha verified
  //do the rest of your validations here
  
});

The code is triggered when the form is submitted. (onsubmit event handler). It checks with recaptcha whether the user has completed the validation.

You must verify the captcha on the server-side as well!

The client-side verification is not enough. It gives immediate response. However, suppose someone is running your form with Javascript disabled. None of these verifications will run and you will keep getting spam submissions.

If you didn’t verify on the server-side that the reCaptcha test was actually run and succeeded, there is no use of the verification itself because the “bots” can still get through your form.

Depending on your server-side scripting language, you have to add a reCaptcha verification step.

These are the steps you have to do on the server: Get the value of this field: g-recaptcha-response Post a request to this endpoint: https://www.google.com/recaptcha/api/siteverify

with these parameters:

  • secret : your secret key that you got while registering with reCaptcha
  • response: the value of the field g-recaptcha-response

If the response is “success”, then the user is verified.

reCaptcha verification PHP code

<?php

$curlx = curl_init();

curl_setopt($curlx, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curlx, CURLOPT_HEADER, 0);
curl_setopt($curlx, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curlx, CURLOPT_POST, 1);

$post_data = 
[
    'secret' => 'ajsdkjhaskdjahskjdhakjhdkjsah', //<--- your reCaptcha secret key
    'response' => $_POST['g-recaptcha-response']
];

curl_setopt($curlx, CURLOPT_POSTFIELDS, $post_data);

$resp = json_decode(curl_exec($curlx));

curl_close($curlx);

if ($resp->success) 
{
    //success!
} else 
{
    // failed
    echo "error";
    exit;
}

See Also