Validate Google reCAPTCHA using JavaScript

Google reCAPTCHA is a popular service for protecting website forms against spam bots. The reCAPTCHA asks users to solve simple puzzles that are easy for humans but hard for bots. Your form should not proceed until the reCAPTCHA puzzle is resolved. This simple technique protects your database from unnecessary spam records. It also saves time as you never get spam comments in your mailbox. No more cleaning of the email inbox.

In order to add a Google reCAPTCHA in website forms, it requires a piece of code. The code should also validate the response of reCAPTCHA. Your website’s form will proceed only for a valid response.

There are 2 ways to validate the response from Google reCAPTCHA – server-side and client-side.

In this article, we focus on client-side validation. We are going to see how to validate Google reCAPTCHA using JavaScript.

If you are looking for server-side validation, please refer to our article Using Google reCAPTCHA On Your Website Forms With PHP.

Register the Site and Get API Keys

To get started, the first step is to register your site with Google reCAPTCHA – https://www.google.com/recaptcha/admin.

google-recaptcha

Choose the option ‘reCAPTCHA v2’ which gives an “I’m not a robot” Checkbox. If you want to test this tutorial on a local server, add localhost as a domain.

Once you enter details in the above form you will get your Site key and Secret key. As we are dealing with the client-side validation, we only need a Site Key. The Secret key is used on server-side validation.

Validate Google reCAPTCHA using JavaScript

Next, let’s see how to add Google reCAPTCHA to your HTML form. You can add it using the code below.

<form method="post" onsubmit="return submitUserForm();">
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="verifyCaptcha"></div>
    <div id="g-recaptcha-error"></div>
    <input type="submit" name="submit" value="Submit" />
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>

Make sure to replace the placeholder ‘YOUR_SITE_KEY’ with your actual site key.

In the above code, I am using the onsubmit event of JavaScript. When a user hits a submit button, we’ll first check the response from the reCAPTCHA and submit a form only if this response is valid.

I also added a verifyCaptcha as a callback function using the data-callback attribute. This callback method is executed when the user submits a successful response(solved a puzzle). The g-recaptcha-response token is passed to your callback.

I used a div with an id g-recaptcha-error to display the error message. The error will populate if users try to submit a form without solving the reCAPTCHA challenge. Upon receiving a successful response, this error will be removed using the callback function.

Now, let’s write a JavaScript code that handles the reCAPTCHA response. Based on the response, it shows either an error message or allows the form to proceed.

<script>
var recaptcha_response = '';
function submitUserForm() {
    if(recaptcha_response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        return false;
    }
    return true;
}

function verifyCaptcha(token) {
    recaptcha_response = token;
    document.getElementById('g-recaptcha-error').innerHTML = '';
}
</script>

The verifyCaptcha method receives a token after users solve the puzzles of reCAPTCHA. I’m assigning this response to the recaptcha_response variable.

In the method submitUserForm, I check if the response is empty. The function will return false for an empty response. It means a user has not yet validated reCAPTCHA. And so, it appends an error to the div element.

When Google reCAPTCHA sends a valid response I am returning a true value, which submits the form for further processing.

Our final code is:

<form method="post" onsubmit="return submitUserForm();">
    <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="verifyCaptcha"></div>
    <div id="g-recaptcha-error"></div>
    <input type="submit" name="submit" value="Submit" />
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
var recaptcha_response = '';
function submitUserForm() {
    if(recaptcha_response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        return false;
    }
    return true;
}

function verifyCaptcha(token) {
    recaptcha_response = token;
    document.getElementById('g-recaptcha-error').innerHTML = '';
}
</script>

I hope you understand how to Validate Google reCAPTCHA using JavaScript. This tutorial should help you to integrate client-side validation of Google reCAPTCHA. Give it a try and share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

22 thoughts on “Validate Google reCAPTCHA using JavaScript

  1. @csrf

    Captcha

    {!! htmlFormSnippet() !!}

    {{– –}}

    Submit
    {{– –}}

    var recaptcha_response = ”;
    function submitUserForm() {
    if(recaptcha_response.length === 0) {
    document.getElementById(‘g-recaptcha-error’).innerHTML = ‘This field is required.’;
    return false;
    }
    return true;
    }

    function verifyCaptcha(token) {
    recaptcha_response = token;
    document.getElementById(‘g-recaptcha-error’).innerHTML = ”;
    }

    This not allows my form to submit.

  2. Hi Thanks for this article. Its very useful. I have added this code in Salesforce Web to Case. Screen wise everything is working fine. But after submitting the form, data is not stored in Salesforce. Any idea? Please advice.

  3. This reaally helps. Thank you!
    But may i know why you did not use the secret key when validating the recaptcha in your code?

    1. We are validating it on the client side. The secret key is required only when we validate it through server side.

Leave a Reply

Your email address will not be published. Required fields are marked *