Created
April 25, 2015 18:08
-
-
Save colecmc/dbacb2df3193069b4236 to your computer and use it in GitHub Desktop.
How to make Google reCAPTCHA a required field? - What you have to do is prevent the form submission until you can validate the user response by using the Google reCaptcha verify callback, then, if it passes, allow the form to submit. Check the documentation: https://developers.google.com/recaptcha/docs/display#example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var RC2KEY = 'sitekey', | |
doSubmit = false; | |
function reCaptchaVerify(response) { | |
if (response === document.querySelector('.g-recaptcha-response').value) { | |
doSubmit = true; | |
} | |
} | |
function reCaptchaExpired () { | |
/* do something when it expires */ | |
} | |
function reCaptchaCallback () { | |
grecaptcha.render('id', { | |
'sitekey': RC2KEY, | |
'callback': reCaptchaVerify, | |
'expired-callback': reCaptchaExpired | |
}); | |
} | |
document.forms['form-name'].addEventListener('submit',function(e){ | |
if (doSubmit) { | |
/* submit form or do something else */ | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi sorry, a bit of a noob here, so I'm certain its basic mistakes, but I was wondering if you could explain the implementation a bit further, I can't quite understand where the google site key goes and so can't get it to render, and where I'm going wrong. Do I change "form-name" to the form ID? I tried the following but couldn't get it to work. The captcha graphic doesn't even show...
The below in the js file:
`<script type="text/javascript">
var RC2KEY = 'sitekey',
doSubmit = false;
function reCaptchaVerify(response) {
if (response === document.querySelector('.g-recaptcha-response').value) {
doSubmit = true;
}
}
function reCaptchaExpired () {
/* do something when it expires */
}
function reCaptchaCallback () {
grecaptcha.render('html_element', {
'sitekey': RC2KEY,
'callback': reCaptchaVerify,
'expired-callback': reCaptchaExpired
});
}
document.forms['form-name'].addEventListener('submit',function(e){
if (doSubmit) {
/* submit form or do something else */
}
})`
Then this in the form:
<div id="html_element"></div>
and this below the form:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer> </script>