Combining Google’s re(no)CAPTCHA and jQuery Validate

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;
               }
           }
       }
   }
});

73 thoughts on “Combining Google’s re(no)CAPTCHA and jQuery Validate”

  1. Hi! Thanks for this script, but I can’t make it work if I’m using multiple reCaptcha in the same page.

    How can I solve it?

    Thanks in advance.

    1. Hey Uriel, if you’re using multiple reCaptchas on the same page, you need to set different and specific ID’s on each reCaptcha. So in the validation instead of selecting a single reCaptcha, you’ll need to select the closest reCaptcha.

      That should solve it, if it doesn’t, could you provide an example?

      Thanks!

      1. A note for anyone trying to validate multiple recaptchas on the same page: I believe you have to pass the recaptcha widgetID to the `getresponse()` method for the validation to work properly, otherwise the first widgetID will always be passed.

        Set your recaptchas, with widgetIDs:
        “`
        var renderRecaptchas = function() {

        widgetID1 = grecaptcha.render(widgetID1, {‘sitekey’: site_key_here});
        widgetID2 = grecaptcha.render(widgetID2, {‘sitekey’: site_key_here});
        }
        “`

        and then pass them on validation:

        “`
        ‘recaptchaFieldName’: {
        required: function(){
        if ( ” === grecaptcha.getResponse( widgetID2 ) ) {
        return true;
        }
        “`

        See https://developers.google.com/recaptcha/docs/display?hl=en

    1. That’s very true, you can use ignore: [] to validate ALL fields, or if you want to selectively ignore hidden fields you can classify the items you want to ignore as I did above, using ignore: ".ignore"

  2. Handling google’s recaptcha by jQuery validate was exactly what i needed, this is awsome! About .ignore, the guys are right, this worked on my end: jQuery(“#orderpoolform”).validate({ ignore: [],…

    Thanks so much!

  3. Hey! Very helpful note, however not working for me 🙁
    When I check (click) the capcha I still see the error message and the form is not submitted. What am I doing wrong there?

    I also have these settings in the validator, but commenting them didn’t help:
    onkeyup: false,
    onclick: false,
    onfocusout: false,

    focusInvalid: false,
    focusCleanup: true

    Would appreciate any help here! Thanks!

  4. Thanks for this… I feel like I’m a big step closer to getting my form to work with the ‘new’ recaptcha.

    In your code, did you intend for the class to be required? Or should it not be required=”required”?

    My issue now is that, if the form element for the hiddenRecaptcha is indeed type=”hidden”, it doesn’t do anything. If I change it to a type=”text”, it works (form won’t submit unless you check the box) but of course, that is not a solution since anyone could enter a bit of text into the hidden field and it would go through.

    Also your solution seems to only confirm that there is a response, but doesn’t check whether that response is true or false. It’s better than nothing, but I’d expect this could fairly easily be bypassed.

    Any help you can provide about why it doesn’t work when the hidden field is hidden would be greatly appreciated.

    1. Hey Robbie, I believe the reason it isn’t working for you on the hidden field is that by default, jQuery Validate doesn’t validate hidden fields. Are you including

      ignore: ".ignore",

      as a parameter when you’re initializing jQuery Validate? That rule tells jQuery validate to validate any field unless it has the class

      ignore

      instead of simply ignoring the hidden fields.

      If you have code to share, I’d be happy to take a look!

  5. Thanks for the simple tutorial!

    My google chrome not working if the if the hiddenRecaptcha type is hidden.

    So have to hide it using style. :

    1. Yes, the hiddenRecaptcha will not validate hidden elements by default, you’ll need to use either the ignore: '.ignore' or ignore: [] parameters in your jQuery Validate instantiation.

  6. I got it to work using this approach. I removed the ignore: “.ignore”,
    and set the CSS for .hiddenRecaptcha to 1px wide; 1px high;

  7. Hi Andrew, I have an Issue about the hidden field.
    I have this: rule ignore:”.ignore, :not(:visible)”,
    to avoid validation in some fields that I hide and show into my form. I think that is obviously why is not validating the captcha hidden field. Do you have any idea to work around this? Thanks, excellent tutorial.

  8. Hi all,
    I just tried validating (multiple) captchas and I was wondering whether triggering a getResponse would have “decorated” the reCaptcha (e.g. in red) in order to show the user that he still need to check a checkbox.
    Since nothing particular happens, why shouldn’t I simply add a “required” constraint to reCaptcha “g-recaptcha-response” textarea?

  9. Would love to get this working on my site, but so far no luck. Anyone have a sec to take a look? Site is not live so feel free to submit the form with test data. Thank you!

    1. Hey Paul, I’m happy to take a look. I opened the form but it doesn’t have ReCaptcha on the page at all. Could you clarify the issue that you’re having?

  10. Hi Andrew,

    first many thanks for tip.
    I integrated it on my side, but now i have the Problem, that the form can’t send.
    jquery.validate don’t see a valid reCaptcha:

    Can you please have a look on my side

    http://develop4.ag-websolutions.de/Review

    It’s a develop-Side, so you can sent the form.

    Best regards

    Gerd

    PS: Sorry for my bad english, my german is better 😉

  11. Is it possible to hide the error message once the getResponse is successful? With the current setup, the error message will only disappear once the form is submitted again (successfully).

    1. Greg, it is possible but that’s actually a feature of jQuery Validate, not the Google ReCaptcha. I would recommend looking into their documentation for hiding the error messages onBlur.

      1. @Andrew…
        first – THANK YOU for this awesome information.

        second – like Greg, i too am having difficulty figuring out how to make the error/highlight be removed when the captcha validates.

        i’ve hunted, as you suggested, for the “onBlur” suggestion, but am still coming up empty. i’m just not figuring it out.
        i’ve google’d & google’d & tried many many variations of ways i’ve found, but nothing has worked for me.

        to be clear: the initial validation DOES work, if i hit the submit button without doing the ReCaptchaV2. but then when i do, the error does not go away even tho the cap successfully gets the green checkmark in it.

        when i watch the code in Chrome DevTools, the hidden input does not get any changes to it when it validates good. i’m wondering if that means there’s a deeper problem.

        so any further help you could give would be greatly appreciated.
        fyi: this form & site is under development @ http://sanctuaryinternational.com/dev/register.html
        ✌?

          1. Very sorry, I’ve been slammed with other things. I tried visiting the URL that you sent and it gave me a 404 error. Do you have an updated link?

  12. Hello. Thanks for your solution but I think it is not very safe because I can execute this code at the page in console and validation will be passed like if I have checked the CAPTCHA:
    grecaptcha.getResponse = function() {return true}

    1. You are absolutely correct Alex! This is just a JavaScript implementation of the Google ReCaptcha. If you want to use a more secure version you need to implement a server side version like with PHP or Ruby.

  13. Hi,

    You said that I have to put the verification for recaptha in the validation function but I don’t have one.

    function myCaptchaFunc(){
    var captcha_response = grecaptcha.getResponse();
    if(captcha_response.length == 0)
    {
    // Captcha is not Passed
    alert(“You have to click the box ‘I\’m not robot'”);
    return false;
    }
    else
    {
    // Captcha is Passed
    alert(“You passed”);
    return true;
    }
    }

    I put that function in my form’s onsubmit attribute, but it doesn’t work.

    1. Are you using jQuery validate? If not, these instructions are specific to the jQuery Validate plugin but there are many other instructions out there for other implementations.

  14. Thanks for the idea, this didn’t work for me with input[type=”hidden”], I had to use a text input and hide it.

  15. I think the correct way to do this might be:

    “g-recaptcha-response”: {
    required: true
    },
    as this is the actual hidden textarea that Google writes to with the result of the reCaptcha.

  16. Also, to validate hidden fields, you need:
    ignore: [],
    as one your validate() settings, because hidden fields are ignored by default..

  17. Thanks for this, this worked for me. So this just ensures the user has checked the CAPTCHA, it does not do a server-side validation with Google, correct? Or does the fact that a value was returned for hiddenRecaptcha mean they are verified?

    1. It does get a server-side response from Google – however – it can be spoofed on the client side if someone knows what they’re doing. This isn’t a true server-side solution.

  18. Thanks for the simple tutorial! its working fine, it gives validation error also,
    but how to remove error message when user click and select google recaptcha ?
    hope for the response

    1. Hi gaurav,

      Please refer below piece of code which help you to remove error message

      var verifyCallback = function () {
      alert(‘Here’);
      // Submit Your Form Here
      };
      var onloadCallback = function () {
      grecaptcha.render(‘example3’, {
      ‘sitekey’: ‘6LcZxAcUAAAAABzfOI3eGVdIxvtyLCsHFhbbJUQ1’,
      ‘callback’: verifyCallback
      });
      };

      1. Hope anyone can help out a little. So far the code from above works well for me. Fact is, that the error message does actually not disappear as expected by the following argument:

        // Validate recaptcha onload explicitly

        var verifyCallback = function() {
        “use strict”;

        // alert(‘Captcha passed’);
        $(‘#hiddenRecaptcha’).valid();

        };

        After gettting a response call which is assigned to the variable any statement should be executed but the error message remains displayed although I’m using .valid() on the hidden field. Nothing. Any idea what could be wrong? thanks for your help. Appreciated.

  19. I’m having a problem with this. My validation error message is displayed whether the CAPTCHA is correctly solved or not. Here’s my code:

    HTML:

    Are you a robot?

    JQUERY:

    jQuery(“#contact”).validate({
    ignore: “.ignore”,
    messages: {
    realname: “Please enter your full name.”,
    email: “Please enter a valid email address.”,
    subject: “Please give your message a subject.”,
    message: “Please enter your message.”,
    hiddenRecaptcha: “Please confirm that you are not a robot.”
    },
    “hiddenRecaptcha”: {
    required: function() {
    if (grecaptcha.getResponse() == ”) {
    return true;
    } else {
    return false;
    }
    }
    }
    });

Leave a Reply

Your email address will not be published.