As I’ve mentioned before, we use jQuery Validate on most sites that we build at work. When validating forms it’s important to do more than just verify that the fields contain values that you’d expect. We should also be testing to verify that the form isn’t spam with a server-side solution like Akismet.

That works great for form submissions, but in the event that we want to prevent spam forms from ever being submitted, it’s easy to add Google reCAPTCHA to jQuery Validate.

  1. Include jQuery on the page.
  2. Include jQuery Validate on the page.
  3. Log into a Google account and register the domain on which you want to install reCAPTCHA.
  4. 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>
  5. 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>
  6. Inside your validation function, add the following new rule:
    1. "hiddenRecaptcha": {
           required: function() {
               if(grecaptcha.getResponse() == '') {
                   return true;
               } else {
                   return false;
               }
           }
      }

That’s really all there is to it! The hidden input allows us to validate the form before it’s actually submitted and integrate it with the existing jQuery Validate code.

Your validation function will likely vary, but a full example would look something like:

var validator = $("#add-conference").validate({
   ignore: ".ignore",
   rules: {
       city: {
           required: function() {
               if ($("#city-name").val()) {
                   return false;
               } else {
                   return true;
               }
           }
       },
       country: {
           required: function() {
               if ($("#country-name").val()) {
                   return false;
               } else {
                   return true;
               }
           }
       },
       "hiddenRecaptcha": {
           required: function() {
               if(grecaptcha.getResponse() == '') {
                   return true;
               } else {
                   return false;
               }
           }
       }
   }
});