Google reCaptcha v2 Client side Validation using JavaScript

Select your language

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

reCaptcha version 2
I will guide you reCaptcha version 2 in this topic. The user is to check a box saying “I am not a robot”. or it shows some picture puzzles too. It generally depends on how the algorithms of Google feels like the user's session is. Most of the time, users get to complete the Captcha just by a checkbox. Here is look of this captcha

recaptcha v2 admin

Preparing for reCaptcha
Go to the reCaptcha site and register for reCaptcha. Remember to enter your domains correct.
recaptcha v2 stop domain check

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)

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

    <title>reCaptcha validation demo</title>
     <script src="" async defer></script>
<div class="form_container">
  <form action="#" id="my_captcha_form">
    <div class="g-recaptcha" 
    <button type="submit" >Submit</button>

First of all I included the reCaptcha api.js from the link

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

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 verify it.

Add this code into script tag, better to include in very last:


var response = grecaptcha.getResponse();
if(response.length == 0)
//reCaptcha not verified
alert("please verify you are humann!");
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.


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 v2 stop domain check