Does anyone know how to make the "Google ReCAPTCHA (v2)" be "required" in a form
?
I mean no form submission until recaptcha is filled-in?
I use ParsleyJs in my form, but didnt find a way to make it work with div
s...
Does anyone know how to make the "Google ReCAPTCHA (v2)" be "required" in a form
?
I mean no form submission until recaptcha is filled-in?
I use ParsleyJs in my form, but didnt find a way to make it work with div
s...
You have to use the reCaptcha verify response call back. Something like this: <script src='https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit'></script>
var RC2KEY = 'sitekey',
doSubmit = false;
function reCaptchaVerify(response) {
if (response === document.querySelector('.g-recaptcha-response').value) {
doSubmit = true;
}
}
function reCaptchaExpired () {
/* do something when it expires */
}
function reCaptchaCallback () {
/* this must be in the global scope for google to get access */
grecaptcha.render('id', {
'sitekey': RC2KEY,
'callback': reCaptchaVerify,
'expired-callback': reCaptchaExpired
});
}
document.forms['form-name'].addEventListener('submit',function(e){
if (doSubmit) {
/* submit form or do something else */
}
})
For ParsleyJS you will to do a little workaround:
1.Add hidden input field, with data-parsley-required="true"
, value = ""
, like this:
<input id="myField" data-parsley-errors-container="#errorContainer" data-parsley-required="true" value="" type="text" style="display:none;">
2.Add error container (just below or under your g-recaptcha
div):
<span id='errorContainer'></span>
3.Add this simple function somewhere in your js code:
function recaptchaCallback() {
document.getElementById('myField').value = 'nonEmpty';
}
4.Add the attribute data-callback
with value of custom function:
<div class="g-recaptcha" data-sitekey="***" data-callback="recaptchaCallback"></div>
You can find another working example here: https://codepen.io/reactionmedia/pen/JVdmbB
For this example I am going to create two HTML elements inside the form:
<div id="botvalidator"></div>
<div id="captchaerrors"></div>
botvalidator will contain the google recaptcha iframe with the "I am not a robot" checkbox inside. captchaerrors will contain errors after checking that user has not clicked on the "I am not a robot" checkbox.
IMPORTANT: We are using arrive.js library in order to know when google recaptcha is adding a new g-recaptcha-response textarea element in the DOM because prior DOM new node insert validations are no longer valid. This event will happen after recaptcha is loaded into the page for a couple of minutes.
You can Download arrive.js library from: https://github.com/uzairfarooq/arrive/
or insert it directly from CDN provider, for example: https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js
Remember to insert ALL libraries after loading JQUERY library to avoid errors. I am using Jquery 2.2.4 version
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
Another important thing is to remember loading recaptcha library in this way, in order to execute onloadCallback function after loading recaptcha and render recaptcha "manually"
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
Here is the code snippet:
var onloadCallback = function() {
/**
* If we try to load page to show the congrats message we don't need to load recaptcha.
*/
if($("#botvalidator").length > 0) {
grecaptcha.render('botvalidator', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
'callback': cleanErrors
});
addCaptchaValidation();
/**
* We are going to use arrive library in order to check new google recaptcha
* element added after the current one is expired and then we will create new attributes for that element.
* Expires-callback google recaptcha is not working, probably it is executed before element creation.
* https://github.com/uzairfarooq/arrive/
*/
$(document).arrive("#g-recaptcha-response", function() {
// 'this' refers to the newly created element
addCaptchaValidation();
});
}
};
/** We are going to remove all errors from the container. */
var cleanErrors = function() {
$("#captchaerrors").empty();
};
var addCaptchaValidation = function() {
console.log("Adding captcha validation");
cleanErrors();
$('#myform').parsley().destroy();
$('#g-recaptcha-response').attr('required', true);
// We are going to create a new validator on Parsley
$('#g-recaptcha-response').attr('data-parsley-captcha-validation', true);
$('#g-recaptcha-response').attr('data-parsley-error-message', "We know it, but we need you to confirm you are not a robot. Thanks.");
$('#g-recaptcha-response').attr('data-parsley-errors-container', "#captchaerrors");
$('#myform').parsley();
};
/** We are going to add a new Parsley validator, this validation is called from
#g-recaptcha-response after clicking the submit button*/
window.Parsley.addValidator('captchaValidation', {
validateString: function(value) {
if(debug) console.log("Validating captcha", value);
if(value.length > 0) {
return true;
} else {
return false;
}
},
messages: {en: 'We know it, but we need you to confirm you are not a robot. Thanks.'}
});
<html>
<head>
</head>
<body>
<h1>Parsley and Google Recaptcha Example</h1>
<form id="myform">
Full name
<input type="text" name="name" id="name" data-parsley-required="true">
<br/>
<div id="botvalidator"></div>
<div id="captchaerrors"></div><br/>
<input type="submit" value="Submit Form">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.8.2/parsley.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
</body>
</html>
That's all folks.
Create a rule https://laravel.com/docs/5.7/validation#custom-validation-rules
Then use it in your controller
// validation
$this->validate( $request, array(
'g_recaptcha_response' => ['required', 'string', new Captcha()]
));
© 2022 - 2024 — McMap. All rights reserved.