Learn how to check if the user already checked the Google Recaptcha field.

If you are new with the Google Recaptcha service you may have already noticed that if you submit your form normally and the user has not solved the recaptcha checkbox the form will be submitted without check if the user has already filled the recaptcha field. 

This happens because this form field (appended via javascript by the Google Recaptcha string) is always empty unless the user checks it (that means doesn't exist till the user solves it).

To prevent this behaviour , according to the Google recaptcha api documentation, when a reCAPTCHA is solved by end user, a new field (g-recaptcha-response) will be populated in HTML.

You can verify the user’s response in one of three ways (two of them of the client side):

Using a callback

Add a new parameter to your reCAPTCHA widget (data-callback) :

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

The data callback parameter expects the name of the function to be executed, in the previous widget the callback function name is callback, therefore the function should be named callback:

function callback(){
    console.log("The user has already solved the captcha, now you can submit your form.");
}

Verify if the response has been already sent

Check the grecaptcha response result :

if(grecaptcha.getResponse().length !== 0){
   console.log("The captcha has been already solved");
}

The grecaptcha object is available in the window, since the google recaptcha api.js file is loaded in your document.

Verify server side

As said previously, the g-recaptcha-response field value will be "" (empty) if the user didn't solved the captcha, therefore just check with your server language if the form field is empty or not.

Example using PHP (note that the method can be different of POST according to your form):

if($_POST["g-recaptcha-response"] != ''){
    // The user solved the recaptcha, now verify it if is a robot using the API.
}

Have fun


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors