Adding multiple Recaptcha and custom form validation with Ajax

It is possible to add multiple Google Recaptcha on single page. Here is an example of adding Google Recaptcha in two different forms and adding custom validation to them. This example illustrates using how response ids are created when rendering of form and later using them to create custom validation on the time of submission of this form. Example uses jQuery to handle form submission events and the action of adding fields dynamically to forms where you don’t have an access to the building or rendering of the form.

[js]
var html_element_id, html_element_2_id;
var onloadCallback = function() {
html_element_id = grecaptcha.render(‘html_element’, {
‘sitekey’ : ‘YOUR_SITE_KEY_HERE’
});
html_element_2_id = grecaptcha.render(‘html_element_2’, {
‘sitekey’ : ‘YOUR_SITE_KEY_HERE’
});
};
$(function() {
$(‘#AnswerDisplayForm’).on(‘submit’, function() {
var response = grecaptcha.getResponse(html_element_id);
console.log(response);
if(response.length == 0) {
alert(‘Please verify human check.’);
return false;
}
return true;
});
$(‘#ContactDisplayForm’).on(‘submit’, function() {
var response = grecaptcha.getResponse(html_element_2_id);
console.log(response);
if(response.length == 0) {
alert(‘Please verify human check.’);
return false;
}
return true;
});
$(‘#AnswerDisplayForm fieldset’).append("<div id=’html_element’></div>");
$(‘#ContactDisplayForm fieldset’).append("<div id=’html_element_2′></div>");
});
[/js]

[html]<script src=’https://www.google.com/recaptcha/api.js?onload=onloadCallback&amp;render=explicit’></script>[/html]

You may also need to reload captcha when using ajax form submissions and encountering validation errors. In this case you may need to represent the entire form along with errors. So the recaptcha is supposed to be recreated. Here is how it can be done..

..after completing ajax call, for example in jQuery:

[js]…
success: function (data, textStatus, jqXHR) {
grecaptcha.reset(html_element_id); //html_element_id is the id of first captcha wrapper.
}
[/js]

5 thoughts on “Adding multiple Recaptcha and custom form validation with Ajax

Leave a Reply