How to check in js that user has checked the checkbox in Google recaptcha?

93,326

Solution 1

Google has a call back option for when the checkbox is checked.

Add this to your form element:

data-callback="XXX"

Example:

<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="== xxxxxx =="></div>

And a disable attribute to your submit button.

Example:

<button id="submitBtn" disabled>Submit</button>

Then a create a callback function and write whatever code you need.

Example:

function recaptchaCallback() {
    $('#submitBtn').removeAttr('disabled');
};

Solution 2

You can also call the grecaptcha object to check. grecaptcha.getResponse(); is empty when unchecked and has the verification code when checked.

grecaptcha.getResponse().length === 0 when unchecked

function isCaptchaChecked() {
  return grecaptcha && grecaptcha.getResponse().length !== 0;
}

if (isCaptchaChecked()) {
  // ...
}

Solution 3

To check if google recaptcha is checked or not you can do it by the following code :

<script>

if(grecaptcha && grecaptcha.getResponse().length > 0)
{
     //the recaptcha is checked
     // Do what you want here
     alert('Well, recaptcha is checked !');
}
else
{
    //The recaptcha is not cheched
    //You can display an error message here
    alert('Oops, you have to check the recaptcha !');
}

</script>

Solution 4

To check if google recaptcha v2 is checked or not you can do it by the following code :

var checkCaptch = false;
     var verifyCallback = function(response) {
        if (response == "") {
             checkCaptch = false;
         }
         else {
             checkCaptch = true;
         }
     };
     $(document).ready(function() {
         $("#btnSubmit").click(function() {
             if (checkCaptch && grecaptcha.getResponse()!="") {
                  //Write your success code here
             }
         });
     })

Solution 5

Let the browser do the job for you! (based on slinky2000 answer)

note: this is only to prevent sending an 'accidentally' unchecked recaptcha. You still have to verify the recaptcha on server side because a bot does not care ...

Add a an invisible input tag with required=true attribute just below the div.g-recaptcha.

<input id='recaptcha_check_empty' required tabindex='-1',
style='width:50px; height:0; opacity:0; pointer-events:none; 
position:absolute; 
bottom:0;'>

Enclose both width a div with position=relative; to point the bottom:0; above to the bottom of recaptcha.

Now the Browser asks nicely to fill out this field - pointing to the recapcha.

Now we need the callback:

<div class="g-recaptcha" data-callback="recaptchaCallback" ...

and

function recaptchaCallback() { 
    $('#recaptcha_check_empty').val(1);
}
Share:
93,326
Hello Universe
Author by

Hello Universe

By day: Project Officer By night: Stargazer, enthusiastic about everything scientific, food taster, and lyfe. Also a very active algo trader

Updated on December 15, 2021

Comments

  • Hello Universe
    Hello Universe over 2 years

    I have added the following before end of head

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

    I have added this before end of form

    <div class="g-recaptcha" data-sitekey="== xxxxxx =="></div>
    

    I can see the recaptcha similar to https://developers.google.com/recaptcha/

    HOwever, when user presses data without checking the checkbox, the data is submitted. Is there any other code I need to add to check if user has pressed the checkbox? Hopefully in js?

  • Nitin Dhomse
    Nitin Dhomse over 7 years
    But, how to get grecaptcha.getResponse()?
  • Olafur Tryggvason
    Olafur Tryggvason over 7 years
    It's loaded as soon as you load google's recaptcha. Part of the package
  • silvachathura
    silvachathura over 7 years
    will that be working if the page has two captcha codes ?
  • silvachathura
    silvachathura over 7 years
    i tried but not working, console debug says>> " Uncaught ReferenceError: grecaptcha is not defined"
  • Denys Klymenko
    Denys Klymenko over 7 years
    script should load recaptcha first, try to do it async or with setTimeout
  • slinky2000
    slinky2000 over 7 years
    Possibly, you would need to add in extra functionality to check if both callbacks where called before enabling the submit button.
  • jaybro
    jaybro about 7 years
    var isCaptchaChecked = (grecaptcha && grecaptcha.getResponse().length !== 0);
  • mohanen b
    mohanen b about 7 years
    The point of having captcha is to avoid scripted access(Bot), But using like this will provide no benefits since it can be bypassed by executing $('#submitBtn').removeAttr('disabled'); in the scripts.
  • halfbit
    halfbit almost 7 years
    @mohanenb: It's just to prevent sending, it's not meant not to check server side like usual.
  • Akshay Kapoor
    Akshay Kapoor over 6 years
    How to tackle timeout problem ? If someone checks the reCaptcha and then don't submit form for few minutes then reCaptcha will expire but user still able to submit the form ..!
  • xinthose
    xinthose over 6 years
    @AkshayKapoor data-expired-callback
  • ForTheWin
    ForTheWin over 6 years
    Just a heads up to place the function recaptchaCallback() outside of document.ready so that it can be reachable by the captcha control. Otherwise, you'll receive a console.log error like "ReCAPTCHA couldn't find user-provided function:".
  • João Pimentel Ferreira
    João Pimentel Ferreira over 5 years
    This indeed answers the OP question. The chosen answer merely calls a function when the captcha is solved, but does not provide a function to check whether the captcha was solved.
  • João Pimentel Ferreira
    João Pimentel Ferreira over 5 years
    This solution merely calls a function when the captcha is solved, but does not provide a function to check whether the captcha was solved.
  • Robert Koernke
    Robert Koernke over 5 years
    The second answer by Olafur should be the accepted answer. For 2 reasons. 1) It's a lot more work. 2) Handling expired validations...
  • Ng Sek Long
    Ng Sek Long about 4 years
    If your grecaptcha is undefined, make sure your explicitly render your recapcha like so https://www.google.com/recaptcha/api.js?onload=onloadRender&‌​render=explicit, more info see: developers.google.com/recaptcha/docs/…
  • Divins Mathew
    Divins Mathew over 3 years
    Validating captcha on client side is a bad idea. Anyone can easily call your callback from the console.
  • slinky2000
    slinky2000 over 3 years
    you of course have to validate the captcha on the server side too. you can't reply in client side validation only.
  • Admin
    Admin almost 3 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • Admin
    Admin almost 3 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.