Last week I wrote about adding reCAPTCHA to jQuery Validator but what if you just want to add it to a regular form? It’s significantly easier to just add re/noCAPTCHA to a form without trying to integrate jQuery Validator. The first few steps are very similar:
- Include jQuery on the page.
- Log into a Google account and register the domain on which you want to install reCAPTCHA.
- Include the following reCAPTCHA script on the page. Preferably with the rest of the JavaScript on the page.
-
<script src='https://www.google.com/recaptcha/api.js'></script>
-
- Paste the following in the
HTML
where you want the reCAPTCHA to show up.-
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha"> <div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
-
- Add the following function to the rest of your JavaScript.
-
$('{YOUR-FORM-SELECTOR}').submit(function(e){ if(grecaptcha.getResponse() == ''){ e.preventDefault(); $('.g-recaptcha').siblings('.error').html('<div class="error">The reCAPTCHA failed, please try again.</div>'); grecaptcha.reset(); }; });
-
Be sure to add an element with the .error class to your form as a sibling of the reCAPTCHA element or handle your errors in another way.