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

JavascriptJqueryCheckboxRecaptcha

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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);
}
		
	

Solution 6 - Javascript

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

Solution 7 - Javascript

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)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHello UniverseView Question on Stackoverflow
Solution 1 - Javascriptslinky2000View Answer on Stackoverflow
Solution 2 - JavascriptOlafur TryggvasonView Answer on Stackoverflow
Solution 3 - JavascriptMustapha GHLISSIView Answer on Stackoverflow
Solution 4 - JavascriptManish VadherView Answer on Stackoverflow
Solution 5 - JavascripthalfbitView Answer on Stackoverflow
Solution 6 - JavascriptLive inView Answer on Stackoverflow
Solution 7 - JavascriptRicardo alvarezView Answer on Stackoverflow