Validate a form with Google Recaptcha and Javascript

If you work with the web, chances are you've run across Google's Recaptcha. You know, the "click to prove you're not a robot" stuff. It's pretty ubiquitous, and even though it's very well documented, there's one case that came up today that bears mentioning: submitting a form directly to an outside service instead of validating it yourself. It's a pretty simple little piece of code, but could easily be overlooked in the thousands of lines of documentation on the Recaptcha software.

So without further ado, code:

<form action="outside-service-url">
    <div id="g-recaptcha"></div>
    <input type="submit" id="submit" disabled value="Submit" />
</form>

The form requires a submit button, obviously; make sure the button starts as disabled so the user can't submit the form until they've validated the captcha. Obviously for more sophisticated users this might require a bit more work to make sure they don't directly edit your code and submit, but for most cases this should work just fine.

<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaLoadCallback&render=explicit' async defer></script>

Next, somewhere at the bottom of the page, include the google recaptcha script. The onload parameter is crucial: it allows us to trigger a callback when the script gets loaded so we can load up and configure out recaptcha exactly the way we want it.

Underneath that, add another script block with the following:

// When the recaptcha is validated, run the following callback
var recaptchaVerifyCallback = function() {
    // Enable the submit button.
    document.getElementById('submit').disabled = false;
}

// This callback gets run when the recaptcha loads.
var recaptchaLoadCallback = function() {
    grecaptcha.render('g-recaptcha', {
        'sitekey': 'your_site_key',
        'callback': recaptchaVerifyCallback
    });
}

This is where we create the actual recaptcha block in our code. We're explicitly rendering it so we can also provide the success callback. After the user clicks the button, it immediately calls the recaptchaVerifyCallback so that we can update the input to actually work and submit the form. Simple right?

Finally, it's probably a good idea to update the UI to reflect the changes we just made; make sure you add in a little CSS that will do something like:

input[type=submit]:disabled {
    background-color: #999;
    cursor: not-allowed;
}

Easy! Obviously you could do a lot more with this. Submitting forms to an internal URL that you can control makes things easier, but if you just have a quick site that needs to submit to an external form, it's a quick and easy way that gives you recaptcha support for most users.

{{ message }}

{{ 'Comments are closed.' | trans }}