Validate Google reCAPTCHA using JavaScript

Google reCAPTCHA is a popular choice for protecting the website forms against spam and bots. The reCAPTCHA asks users to solve simple puzzles that are easy for humans but hard for bots. As a result, one can save their server space from inserting unnecessary spam records into the database. It also saves us time as we never get spam comments in our mailbox.

When we add a Google reCAPTCHA in website forms, we need to write a piece of code to validate the response of reCAPTCHA. If a response is valid then only our 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 so we study how to validate Google reCAPTCHA using JavaScript.

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

Register the Site and Get API Keys

For getting started, you need to register your site here – https://www.google.com/recaptcha/admin.

google-recaptcha

Choose the option ‘reCAPTCHA v2’ which gives an “I’m not a robot” Checkbox.

Once you entered 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.

If you want to test it on a local server then add ‘localhost’ as a domain.

Validate Google reCAPTCHA using JavaScript

First, you need to add Google reCAPTCHA on 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>

In the above code, I am using onsubmit event. This is because when the user submits a form we need to check the reCAPTCHA response and then allow it to submit a form.

Then I added a ‘verifyCaptcha’ as a name of a callback function to the attribute ‘data-callback’. I will use this callback method to remove the error message once the validation is passed. I also added a div with an id ‘g-recaptcha-error’ to display the error message.

You should replace the placeholder ‘YOUR_SITE_KEY’ with your actual site key.

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>
function submitUserForm() {
    var response = grecaptcha.getResponse();
    if(response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        return false;
    }
    return true;
}

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

In the method submitUserForm we get the reCAPTCHA response using grecaptcha.getResponse(). This is a built-in function provided by Google reCAPTCHA service.

If the response is invalid then it returns 0. It means a user has not yet validated reCAPTCHA. And so, it throws an error and appends to the div which has id ‘g-recaptcha-error’.

When Google reCAPTCHA sends a valid response I am returning a true value, which allows the form to proceed further.

The verifyCaptcha method gets a call when you solve all the puzzles of reCAPTCHA. We are then removing the error message once a puzzle is solved.

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>
function submitUserForm() {
    var response = grecaptcha.getResponse();
    if(response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        return false;
    }
    return true;
}

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

I hope you understand how to Validate Google reCAPTCHA using JavaScript. Try it in your project 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.

17 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 *