How to Validate Google reCaptcha on Form Submit
If you want to check if the User clicked on the I'm not a robot
checkbox, you can use the .getResponse()
function provided by the reCaptcha API.
It will return an empty string in case the User did not validate himself, something like this:
if (grecaptcha.getResponse() == ""){
alert("You can't proceed!");
} else {
alert("Thank you");
}
In case the User has validated himself, the response will be a very long string.
More about the API can be found on this page: reCaptcha Javascript API
Require User to click google's new recaptcha before form submission
You can check the textarea field with id g-recaptcha-response
. You can do as following:
$("form").submit(function(event) {
var recaptcha = $("#g-recaptcha-response").val();
if (recaptcha === "") {
event.preventDefault();
alert("Please check the recaptcha");
}
});
Hope this helps you.
Validating submit of form with Google reCAPTCHA
You need to trigger your if
statement in an event. If you're using jQuery you can do this very easily:
$('form').on('submit', function(e) {
if(grecaptcha.getResponse() == "") {
e.preventDefault();
alert("You can't proceed!");
} else {
alert("Thank you");
}
});
See working example here: JSFiddle
The problem with doing this in JavaScript at all is that the user can easily fake the result if they want to. If you really want to be checking if the user is a robot or not, you should still be comparing the result submitted by the user (via POST) on the server side using your reCAPTCHA secret key.
How can i vaalidate Google reCaptcha on HTML form submit button
You cannot validate captcha on the client (browser), so you cannot validate it before submit.
Captcha validation has to be done on the server, after the form is submitted, as it involves calling google with their API to validate that the captcha was answered correctly Refer to this page on how to do this verification: https://developers.google.com/recaptcha/docs/verify.
HTML5 form validation before reCAPTCHA's
You have to do it programmatically thanks to a new v2 grecaptcha
method: grecaptcha.execute()
so that recaptcha doesn't replace the button's default click event which was preventing the default HTML5 form validation.
The event path is:
- Submit button click event: browser built-in form validation
- Form submit event: call
grecaptcha.execute()
- reCAPTCHA callback: submit the form
$('#form-contact').submit(function (event) { event.preventDefault(); grecaptcha.reset(); grecaptcha.execute(); });
function formSubmit(response) { // submit the form which now includes a g-recaptcha-response input}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://www.google.com/recaptcha/api.js"></script><form action="?"> <div class="g-recaptcha" data-sitekey="your-key" data-size="invisible" data-callback="formSubmit"> </div> <button type="submit">Submit</button></form>
How do I perform HTML form validation with Google ReCaptcha V2 Invisible AND Multiple Forms?
After a lot of searching, I finally found a solution that works and is rather elegant in the fact that it supports multiple forms on a single page, and is dynamic. It searches the page and attaches the recaptcha to any matching tagged divs. It should support as many forms as you like on one page.
This is the tag it attaches to:
<div class="recaptcha-holder"></div>
I am still unsure why my own implementation did not work. Every time I had recaptcha attached to multiple forms, the server-side processing would fail, and debugging showed it was not receiving recaptcha data.
Just a note, this is being implemented on a WordPress site, so I am adding the javascript to my existing js include that I put my custom code in.
This code is the last entry on this question (Implement the new Invisible reCaptcha from Google) posted by Mch (https://stackoverflow.com/users/7327512/mch). All thanks goes to them for the front-end solution. Funny enough it was posted at the very end of 2016.
Mch's Front-End Example
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input type="text" name="first-name-1"> <br />
<input type="text" name="last-name-1"> <br />
<div class="recaptcha-holder"></div>
<input type="submit" value="Submit">
</form>
<br /><br />
<form action="" method="post">
<input type="text" name="first-name-2"> <br />
<input type="text" name="last-name-2"> <br />
<div class="recaptcha-holder"></div>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=renderGoogleInvisibleRecaptcha&render=explicit" async defer></script>
</body>
</html>
Mch's Javascript (Added to my existing JS include)
var renderGoogleInvisibleRecaptcha = function() {
for (var i = 0; i < document.forms.length; ++i) {
var form = document.forms[i];
var holder = form.querySelector('.recaptcha-holder');
if (null === holder){
continue;
}
(function(frm){
var holderId = grecaptcha.render(holder,{
'sitekey': 'CHANGE_ME_WITH_YOUR_SITE_KEY',
'size': 'invisible',
'badge' : 'bottomright', // possible values: bottomright, bottomleft, inline
'callback' : function (recaptchaToken) {
HTMLFormElement.prototype.submit.call(frm);
}
});
frm.onsubmit = function (evt){
evt.preventDefault();
grecaptcha.execute(holderId);
};
})(form);
}
};
And finally my Back-End (server side) processing:
<?php
// reCaptcha info
$secret = "MySecretKey";
$remoteip = $_SERVER["REMOTE_ADDR"];
$url = "https://www.google.com/recaptcha/api/siteverify";
// Form info
$first = $_POST["first"];
$last = $_POST["last"];
$response = $_POST["g-recaptcha-response"];
// Curl Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
));
$curlData = curl_exec($curl);
curl_close($curl);
// Parse data
$recaptcha = json_decode($curlData, true);
if ($recaptcha["success"])
{
// MY DATA VALIDATION & EMAILING OF FORM DATA
}else{
// Google ReCaptcha Failed to Verify - Send to False Positive
header('Location: /thank-you-for-contacting-us/?gvx');
exit;
}
?>
Related Topics
Show Hide Payment Methods Based on Selected Shipping Method in Woocommerce
Optimizing Kohana-Based Websites for Speed and Scalability
Leverage Browser Caching, How on Apache or .Htaccess
How to Debug Why Simplest MySQL Query Returns False
Why Use Sprintf Function in PHP
In PHP What Does It Mean by a Function Being Binary-Safe
Why a Function Checking If a String Is Empty Always Returns True
Show Stock Status Next to Each Attribute Value in Woocommerce Variable Products
How to Display PHP & HTML Source Code on a Page
PHP Tree Structure for Categories and Sub Categories Without Looping a Query
How to Install Composer Globally on Windows
How to Save Webpage as a Image File Using PHP