Adding re(no)CAPTCHA to forms

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:

  1. Include jQuery on the page.
  2. Log into a Google account and register the domain on which you want to install reCAPTCHA.
  3. Include the following reCAPTCHA script on the page. Preferably with the rest of the JavaScript on the page.
    1. <script src='https://www.google.com/recaptcha/api.js'></script>
  4. Paste the following in the HTML where you want the reCAPTCHA to show up.
    1. <input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
      <div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
  5. Add the following function to the rest of your JavaScript.
    1. $('{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.

Leave a Reply

Your email address will not be published.