Validate Google reCAPTCHA using JavaScript

Google reCAPTCHA is a popular service for protecting website forms against spam and 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 challenge is resolved. Ultimately it saves the server space from inserting unnecessary spam records into the database. It also saves us time as we never get spam comments in our mailbox. So no more cleaning up of the email inbox.

To add a Google reCAPTCHA in website forms, it needs to write a piece of code to validate the response of reCAPTCHA. If a response is valid then only the form should proceed.

There are 2 ways to validate the response – one is server-side and the other is client-side. In this article, we focus on client-side validation and thus we study how to validate Google reCAPTCHA using JavaScript.
If you are looking for server-side validation, please refer to the article Using Google reCAPTCHA On Your Website Forms With PHP.

Register the Site and Get API Keys

To get started, you need 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 then 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.

Validate Google reCAPTCHA using JavaScript

Next, you need to add Google reCAPTCHA to your form. You can do 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>

Replace the placeholder ‘YOUR_SITE_KEY’ with your actual site key.

In the above code, I am using the onsubmit JavaScript event. This is because when a user hits a submit button, we need to check first reCAPTCHA response and then actually submit a form.

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. 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. It will populate if users try to submit a form without solving the reCAPTCHA challenge. Upon receiving a successful response, I will remove the error message from the callback function. 

Finally, let’s write a JavaScript code that handles the reCAPTCHA response. And 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. We are assigning this response to the <code>recaptcha_response</code> variable.

In the method <code>submitUserForm</code>, I check if the response is empty. It returns ‘false’ for an empty response. It means a user has not yet validated reCAPTCHA. And so, it appends an error to the div having the id ‘g-recaptcha-error’.

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. Give it a try and share your thoughts or suggestions in the comment section below.

Related Articles

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

19 thoughts on “Validate Google reCAPTCHA using JavaScript

  1. 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.

  2. 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.

    1. Receiving my cash reward cards for PayPal and I haven’t received anything either in mail are on my account still reviewing my cash app my rewards and there isn’t any transaction yetof my Winnie’s I. My cash acount

Leave a Reply

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