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?

4

7 Answers 7

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');
};
11
  • 1
    @mohanenb: It's just to prevent sending, it's not meant not to check server side like usual.
    – halfbit
    Jul 10, 2017 at 17:25
  • 2
    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 ..! Oct 20, 2017 at 12:50
  • 3
    @AkshayKapoor data-expired-callback
    – xinthose
    Nov 2, 2017 at 14:59
  • 5
    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:".
    – ForTheWin
    Feb 20, 2018 at 4:33
  • 1
    This solution merely calls a function when the captcha is solved, but does not provide a function to check whether the captcha was solved. Oct 29, 2018 at 10:29
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()) {
  // ...
}
7
  • But, how to get grecaptcha.getResponse()? Jan 13, 2017 at 6:46
  • It's loaded as soon as you load google's recaptcha. Part of the package Jan 14, 2017 at 12:32
  • i tried but not working, console debug says>> " Uncaught ReferenceError: grecaptcha is not defined" Jan 18, 2017 at 10:29
  • script should load recaptcha first, try to do it async or with setTimeout Jan 18, 2017 at 12:18
  • 2
    var isCaptchaChecked = (grecaptcha && grecaptcha.getResponse().length !== 0);
    – jaybro
    Jun 6, 2017 at 15:44
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>
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);
}
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
             }
         });
     })
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>
2
  • 3
    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.
    – Community Bot
    Sep 16, 2021 at 6:55
  • 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.
    – Community Bot
    Sep 16, 2021 at 13:43
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)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.