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

7

98

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?

Steddman answered 23/2, 2015 at 13:31 Comment(4)
did you read this page: developers.google.com/recaptcha/docs/verifyAldenalder
yeep.. cant seem to figure out how to get this working thoughSteddman
you should request that on your backend server. it wouldn't be very safe for the browser to do it alone.Aldenalder
That is fine. How to request that from front end maybe using jquery?Steddman
F
205

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');
};
Fulgurous answered 23/2, 2015 at 14:28 Comment(11)
will that be working if the page has two captcha codes ?Precincts
Possibly, you would need to add in extra functionality to check if both callbacks where called before enabling the submit button.Fulgurous
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.Molton
@mohanenb: It's just to prevent sending, it's not meant not to check server side like usual.Transitive
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 ..!Taeniacide
@AkshayKapoor data-expired-callbackSnowplow
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:".Rositaroskes
This solution merely calls a function when the captcha is solved, but does not provide a function to check whether the captcha was solved.Babushka
The second answer by Olafur should be the accepted answer. For 2 reasons. 1) It's a lot more work. 2) Handling expired validations...Lopes
Validating captcha on client side is a bad idea. Anyone can easily call your callback from the console.Winnie
you of course have to validate the captcha on the server side too. you can't reply in client side validation only.Fulgurous
B
82

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()) {
  // ...
}
Bhang answered 2/6, 2015 at 9:4 Comment(7)
But, how to get grecaptcha.getResponse()?Fenelia
It's loaded as soon as you load google's recaptcha. Part of the packageBhang
i tried but not working, console debug says>> " Uncaught ReferenceError: grecaptcha is not defined"Precincts
script should load recaptcha first, try to do it async or with setTimeoutHesitate
var isCaptchaChecked = (grecaptcha && grecaptcha.getResponse().length !== 0);Dogma
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.Babushka
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/…Communicate
F
14

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>
Fuhrman answered 22/10, 2017 at 11:17 Comment(0)
T
4

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);
}
Transitive answered 10/7, 2017 at 17:14 Comment(0)
C
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
             }
         });
     })
Cherycherye answered 20/6, 2018 at 5:18 Comment(0)
J
0
<div class="contact-inner contact-message">
  <label for="message-text" class="col-form-label">CAPTCHA</label>
  <div class="g-recaptcha" data-sitekey="<?php echo 6LfSJmocAAAAAFFMpMKB1CtYNJYDyDswO7GpxRXS ;?>">
  </div>
</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
<!DOCTYPE html>
<html>
  <head>
    <title>CAPTCHA</title>
  </head>
  <body>
      <div class="contact-inner contact-message">
        <label for="message-text" class="col-form-label">CAPTCHA</label>
        <div class="g-recaptcha" data-sitekey="<?php echo GOOGLE_KEY ;?>"></div>
      </div>
  </body>
</html>
Joanjoana answered 16/9, 2021 at 6:44 Comment(2)
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.Coequal
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.Coequal
D
0

if for some reason you are conditioning a form by hand like me, and required is not working.

First import ReCAPTCHA

import  ReCAPTCHA  from 'react-google-recaptcha'

Apply it in your component

<ReCAPTCHA style={{margin: '5px', transform: 'scale(0.8)'}} ref={recaptchaRef} sitekey={recaptchaKey} onChange={updateRecaptcha}/>

you can use a useRef or just use the ReCAPTCHA you've imported, I used useRef.

const recaptchaRef = useRef<any>()

And now, how do I check if recaptchaRef is checked?

if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
    //your condition
}

basically, you are saying 'if recaptcha is true, then do this'

this is complete form code that helps you (I'm using typeScipt)

const Formid = // yout formid
const FormSpark = `https://submit-form.com/${Formid}`

type FormState =  {
    name: string,
    mail: string,
    message: string
}
const initialState = {
    name: '',
    mail: '',
    message: '',
}

const [wrongmail, setWrongmail] = useState(false)
const [wrongname, setWronname] = useState(false)
const [wrongtext, setWrongtext] = useState(false)
const [alert, setAlert] = useState(false)
const recaptchaRef = useRef<any>()
const recaptchaKey = //your recaptcha public key    const [recaptchaToken, setRecaptchaToken] = useState<string>()
const [formstate, setFormState] = useState<FormState>(initialState)
const submit = async(event: FormEvent) =>{
    event.preventDefault()
    await postSubmission()
}
const updateRecaptcha = (token: string | null)=>{
    setRecaptchaToken(token as string)
}
const {name, mail, message} = formstate
const postSubmission = async() => {
    const payload = {
        ...formstate,
        "g-recaptcha-response": recaptchaToken
    }
    try {
        if (name && mail && message) {
            if (mail.includes('@') && mail.includes('.') && mail.length > 5) {
                if (name.includes(' ') && name.length> 5) {
                    if (message.length > 20) {
                        if (recaptchaRef.current) {
                            if (recaptchaRef.current.props.grecaptcha.getResponse().length !== 0) {
                                console.log('hola')
                                setAlert(true)
                                const result = await axios.post(FormSpark, payload)
                                setFormState(initialState)
                                recaptchaRef.current.reset()
                                if (result) {
                                    setTimeout(() => {
                                        setAlert(false)
                                    },2000)
                                }
                            }
                        }
                    }
                }
            }
            if (!name && !(name.length> 5) && !(name.includes(' '))) {
                setWronname(true)
                setTimeout(() => {
                    setWronname(false)
                },3000)
            }
            if (!mail && !mail.includes('@') && !mail.includes('.') && !(mail.length > 5)) {
                setWrongmail(true)
                setTimeout(()=>{
                    setWrongmail(false)
                },3000)
            }
            if (!message && !(message.length > 20)) {
                setWrongtext(true)
                setTimeout(() => {
                    setWrongtext(false)
                },3000)
            }
        }
    } catch(error){
        console.log(error);
    }
}

const updateForm = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const {id, value} = event.target
    const formKey = id as keyof FormState
    const updatedFormState = {...formstate}
    updatedFormState[formKey] = value
    setFormState(updatedFormState)
}
Dyche answered 26/2, 2022 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.