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.
- Include jQuery on the page.
- Include jQuery Validate 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>
-
- Inside your validation function, add the following new rule:
-
"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; } } } } });
[…] 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 […]
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.
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!
How can select next recaptcha to get its response
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
Dude! This was really useful. Worked for me.
Also @zgreen comment from Aug 18th.
Thanks!
jQuery validation ignores hidden fields since version 1.9. You can un-ignore them by option “ignore: []”. See:
http://stackoverflow.com/questions/8466643/jquery-validate-enable-validation-for-hidden-fields
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, usingignore: ".ignore"
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!
Glad it helped!
Not working
This was by far the simplest solution for my needs. Thank you!
Glad it helped, Ezra!
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!
Hey Greg, do you have any code I could look at and help you debug?
Hi,
I test it and not work! can u create demo ?!
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.
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
as a parameter when you’re initializing jQuery Validate? That rule tells jQuery validate to validate any field unless it has the class
instead of simply ignoring the hidden fields.
If you have code to share, I’d be happy to take a look!
Or as Baltazarz3 mentioned below, you could use
ignore: []
to validate all fields, hidden or otherwise.please provide the working form to download i am bit confused
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. :
Yes, the hiddenRecaptcha will not validate hidden elements by default, you’ll need to use either the
ignore: '.ignore'
orignore: []
parameters in your jQuery Validate instantiation.I got it to work using this approach. I removed the ignore: “.ignore”,
and set the CSS for .hiddenRecaptcha to 1px wide; 1px high;
Depending on your version of jQuery Validate, you could also set
ignore: []
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.
Never mind, I figured out.
ignore:”.ignore, :not(:visible,.hiddenRecaptcha)”,
Thanks anyways.
Thanks for this tip! Helped a lot!
Awesome!! its working perfectly for me 🙂
Glad to hear it!
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?
[…] using jquery.form, , want add together google’s v2 captcha, have followed illustration here, it’s not validating. finish captcha still “this field required” message when […]
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!
Site is here: http://ehslax50.com/register.asp
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?
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 😉
Gerd, I took a look and it actually seems to be working just fine!
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).
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.
@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
✌?
Thanks for the input Jason! I’ll take a look at this tonight and get back to you.
any luck?
hi Andrew,
any luck on this yet?
THANKS so much!
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?
This can be done by the data-callback attribute and a simple callback function:
function recaptchaCallback() {
$(“#hiddenRecaptcha”).valid();
}
http://stackoverflow.com/questions/28674946/how-to-check-in-js-that-user-has-checked-the-checkbox-in-google-recaptcha
http://stackoverflow.com/questions/17844136/revalidate-an-element-when-changed-programmatically-with-javascript
is it possible hide the images popup
Unfortunately no, the images popup is what the Captcha uses to verify that the user isn’t a bot.
is it possible to enter the text instead of images popup. if it is possible, how we can made it.
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}
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.
Thanks for posting this. It worked perfectly for me.
How to check Recaptcha status in custom java-script method instead jquery validation rules?
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.
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.
Thanks for the idea, this didn’t work for me with input[type=”hidden”], I had to use a text input and hide it.
That perfectly worked.
Really thanks for sharing this tutorial.
Regards
A WP Life
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.
this works fine, just trying to figure out how to display message of missing human verification
Also, to validate hidden fields, you need:
ignore: [],
as one your validate() settings, because hidden fields are ignored by default..
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?
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.
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
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
});
};
please check this link you will get it
https://developers.google.com/recaptcha/docs/display
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.
just found this article, life saver man! thanks!
should like:
ie: required is NOT a class
Shouldn’t required be out side the CLASS?
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;
}
}
}
});
Hi, thanks for the script. its work perfect
This article really helps me. Thanks