How can I validate google reCAPTCHA v2 using javascript/jQuery?

359,606

Solution 1

This Client side verification of reCaptcha - the following worked for me :

if reCaptcha is not validated on client side grecaptcha.getResponse(); returns null, else is returns a value other than null.

Javascript Code:

var response = grecaptcha.getResponse();

if(response.length == 0)
    //reCaptcha not verified

else
    //reCaptch verified

Solution 2

Use this to validate google captcha with simple javascript.

This code at the html body:

<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
        document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

Solution 3

If you render the Recaptcha on a callback

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

using an empty DIV as a placeholder

<div id='html_element'></div>

then you can specify an optional function call on a successful CAPTCHA response

var onloadCallback = function() {
    grecaptcha.render('html_element', {
      'sitekey' : 'your_site_key',
      'callback' : correctCaptcha
    });
  };

The recaptcha response will then be sent to the 'correctCaptcha' function.

var correctCaptcha = function(response) {
    alert(response);
};

All of this was from the Google API notes :

Google Recaptcha v2 API Notes

I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.

Hope this helps.

Paul

Solution 4

Simplified Paul's answer:

Source:

<script src="https://www.google.com/recaptcha/api.js"></script>

HTML:

<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>

JS:

var correctCaptcha = function(response) {
        alert(response);
    };

Solution 5

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.

  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
  <script>
    $("#contactForm").validate({
      submitHandler: function (form) {
        var response = grecaptcha.getResponse();
        //recaptcha failed validation
        if (response.length == 0) {
          $('#recaptcha-error').show();
          return false;
        }
          //recaptcha passed validation
        else {
          $('#recaptcha-error').hide();
          return true;
        }
      }
    });
  </script>
Share:
359,606
Mahatma Aladdin
Author by

Mahatma Aladdin

Analogue at birth, digital by design. Wearing the entrepreneur hat this week and starting a new business. great plan of attack but no product yet. a dream told me to find the product in a dream.

Updated on January 01, 2022

Comments

  • Mahatma Aladdin
    Mahatma Aladdin over 2 years

    I have a simple contact form in aspx. I want to validate the reCaptcha (client-side) before submitting the form. Please help.

    Sample code:

        <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
        <!DOCTYPE html>
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
            <title>Test Form</title>
            <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
            <script src="//code.jquery.com/jquery-1.10.2.js"></script>
            <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
            <link rel="stylesheet" href="/resources/demos/style.css">
            <script src="https://www.google.com/recaptcha/api.js" async defer></script>
            <script>
                $("#cmdSubmit").click(function () {
                    //need to validate the captcha
                });
            </script> 
        </head>
        <body>
            <form id="form1" runat="server">
                <label class="clsLabe">First Name<sup>*</sup></label><br />
                <input type="text" id="txtFName" name="txtFName" class="clsInput" /><br />
                <div class="g-recaptcha" data-sitekey="my_key"></div>
                <img id="cmdSubmit" src="SubmitBtn.png" alt="Submit Form" style="cursor:pointer;" />
            </form>
        </body>
        </html>
    

    I want to validate the captcha on cmdSubmit click.

    Please help.

  • Pravin Sharma
    Pravin Sharma over 9 years
    <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div> this code just above the span tag in body section
  • tdc
    tdc about 9 years
    scratch that, I figured it out -- part of your code is incorrect so I will propose an edit. Cheers!
  • Lightbulb1
    Lightbulb1 about 9 years
    I think this is the better solution. This way you can handle the validation of the response in your form submit handler. This seems more logical than trying to handle it on the captcha callback. I guess it depends if your validating on the fly or at submit.
  • thanks_in_advance
    thanks_in_advance about 9 years
    @Prefix Did you propose the edit yet? Looking forward to your version.
  • slikts
    slikts almost 9 years
    You should use === and !==; no reason not to.
  • Junior Mayhé
    Junior Mayhé almost 9 years
    I notice there is a textarea rendered. So, you could just use document.getElementById('g-recaptcha-response').value=='') document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
  • Pratul Sanwal
    Pratul Sanwal over 8 years
    The correctCaptcha callback function declaration (inside grecaptcha.render) should be without quotes and should be placed before the onloadCallback.
  • Vyacheslav
    Vyacheslav over 8 years
    This doesn't for for multilingual support.
  • Mahmut EFE
    Mahmut EFE almost 8 years
    This solution is wrong. I think when you get response, you have to send parameter(response + secretkey + ClientIp) to the google for the validation. After validation. Google returns us success or fail. in your example, you dont use the second step. can you explain me: Where is your private key. When will you use?
  • Michael Fever
    Michael Fever almost 8 years
    I am not understanding the second line, there is an span tag opening but never closing? <span id="captcha" style="margin-left:100px;color:red" /> ??
  • Sean Kendle
    Sean Kendle over 7 years
    Mahmut is correct, this answer is dangerously wrong and incomplete.
  • Sean Kendle
    Sean Kendle over 7 years
    This is incorrect. The Captcha has NOT been verified by JS, you need to submit the response, along with your site key and secret key, to Google's servers from your back end code in order to determine if the Captcha was successfully answered. This answer is dangerously incorrect.
  • Sean Kendle
    Sean Kendle over 7 years
    @MichaelFever - It's a self-closing span tag, hence the /> at the end. It's invalid HTML, only valid in XML.
  • CoalaWeb
    CoalaWeb about 7 years
    Quote: When a reCAPTCHA is solved by end user, a new field (g-recaptcha-response) will be populated in HTML. developers.google.com/recaptcha/docs/verify
  • Dylan Smith
    Dylan Smith over 6 years
    But that's not all @CoalaWeb ! Quote: After you get the response token, you need to verify it with reCAPTCHA using the following API to ensure the token is valid. https://developers.google.com/recaptcha/docs/verify
  • evolross
    evolross over 6 years
    Like many of the other wrong solutions, you're just getting the token here. You haven't validated it until you send it to Google with your secret key.
  • evolross
    evolross over 6 years
    It would be nice if there was a way to do some sort of "lite" validation on the client before sending to the server for real validation. That way you don't bog down your server with TONS of spam bots sending bad reCaptcha answers. That's what led me to this question.
  • Finlay Roelofs
    Finlay Roelofs over 6 years
    Those bots could easily be adapted to trick the client-side verification though
  • Alex Gurskiy
    Alex Gurskiy over 6 years
    So, like this: return res && res.length don't forget about the server validation.
  • rococo
    rococo over 6 years
    To those saying the answer is not correct, did you even read the question? The question and answer both clearly specify client-side - the obvious intention is to check that the captcha was actually filled in client-side before sending a post request to the server for further validation..
  • Faris Rayhan
    Faris Rayhan over 6 years
    Ya this answer is actually same like above. The things is you get the response by accessing the key from grecaptcha object
  • Faris Rayhan
    Faris Rayhan over 6 years
    This somehow causing problem in my element. Webpack can not compiled it self if we use data-callback inside the element
  • Askerman
    Askerman over 6 years
    This should be the accepted answer as it doesn't require overwriting the render function. As for validation purely in JS, I doubt that is possible as it would require placing the secret key into the JS and thus allowing everyone to get their hands all over it.
  • user151496
    user151496 about 6 years
    @SeanKendle you misunderstood the question. when your user submits unfinished/bad captcha you want to let him know before submitting the form and redirecting him away from the site. this is a fully valid scenario
  • Sean Kendle
    Sean Kendle about 6 years
    Fair, but it's very important to make some mention of the back end also validating against Google's servers. I don't want someone to come here, think that Recaptcha is a client-side-only solution, and neglect to check the answer against Google's servers.
  • Abhishek
    Abhishek over 5 years
    @SeanKendle Is it always a compulsion to use Server side coding for recaptcha verification. Can I know on the client side if the Recaptcha response is a success ?
  • Sean Kendle
    Sean Kendle over 5 years
    You can only know if the user has actually filled it out on the client side. The value of 'g-recaptcha-response' will be filled out, but that needs to be sent to Google for them to check if the response is valid or not. For example, with the image matching, you could click anything or nothing, and click submit. That's not correct, but the value of 'g-recaptcha-response' is filled out. You could use AJAX to verify it, but be sure to keep your secret key in the server side code. Short answer is the server has to check if it's valid, whether you do so with AJAX or with a full form post.
  • Mike W
    Mike W over 4 years
    why does the validation need to be done server side?
  • clayRay
    clayRay about 4 years
    Instead of bothering with two stages of validation and Ajax calls, the simplest way would be to combine both validations as per this article
  • Kaushik shrimali
    Kaushik shrimali about 4 years
    Do more with server side validation
  • Matthew
    Matthew about 4 years
    @MikeW Validation must be done client side because you can never trust a web client; it is out of your control and a malicious user may have altered the data.
  • themissionmars
    themissionmars about 2 years
    This is incorrect. You still need to verify the response token.