jQuery 谷歌 ReCAPTCHA 如何制作必填?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29612879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google ReCAPTCHA how to make required?
提问by serhio
Does anyone know how to make the "Google ReCAPTCHA (v2)" be "required" in a form
?
有谁知道如何使“ Google ReCAPTCHA (v2)”成为“必需” form
?
I mean no form submission until recaptcha is filled-in?
我的意思是在填写 recaptcha 之前不提交表单?
I use ParsleyJs in my form, but didnt find a way to make it work with div
s...
我以我的形式使用 ParsleyJs,但没有找到使它与div
s 一起工作的方法...
回答by colecmc
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>
您必须使用 reCaptcha 验证响应回调。像这样的东西:<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 */
}
})
回答by Shahar Shokrani
For ParsleyJSyou will to do a little workaround:
对于ParsleyJS,您需要做一些解决方法:
1.Add hidden input field, with data-parsley-required="true"
, value = ""
, like this:
1.添加隐藏输入框,用data-parsley-required="true"
, value = ""
,像这样:
<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):
2.添加错误容器(就在您的g-recaptcha
div下方或下方):
<span id='errorContainer'></span>
3.Add this simple function somewhere in your js code:
3.在你的js代码的某处添加这个简单的函数:
function recaptchaCallback() {
document.getElementById('myField').value = 'nonEmpty';
}
4.Add the attribute data-callback
with value of custom function:
4.添加data-callback
自定义函数值的属性:
<div class="g-recaptcha" data-sitekey="***" data-callback="recaptchaCallback"></div>
回答by libnac
You can find another working example here: https://codepen.io/reactionmedia/pen/JVdmbB
您可以在此处找到另一个工作示例:https: //codepen.io/reactionmedia/pen/JVdmbB
For this example I am going to create two HTML elements inside the form:
对于这个例子,我将在表单中创建两个 HTML 元素:
<div id="botvalidator"></div>
<div id="captchaerrors"></div>
botvalidatorwill contain the google recaptcha iframe with the "I am not a robot" checkbox inside. captchaerrorswill contain errors after checking that user has not clicked on the "I am not a robot" checkbox.
botvalidator将包含带有“我不是机器人”复选框的 google recaptcha iframe。 captchaerrors将包含错误后,检查用户对“我不是机器人”复选框并没有点击。
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.
重要提示:我们使用到达.js 库是为了知道 google recaptcha 何时在 DOM 中添加新的 g-recaptcha-response textarea 元素,因为之前的 DOM 新节点插入验证不再有效。此事件将在 recaptcha 加载到页面几分钟后发生。
You can Download arrive.js library from: https://github.com/uzairfarooq/arrive/
您可以从以下位置下载到达.js 库:https: //github.com/uzairfaooq/arrive/
or insert it directly from CDN provider, for example: https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js
或直接从 CDN 提供商插入,例如: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
请记住在加载 JQUERY 库后插入所有库以避免错误。我使用的是 Jquery 2.2.4 版本
<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"
另一个重要的是记住以这种方式加载recaptcha库,以便在加载recaptcha后执行onloadCallback函数并“手动”渲染recaptcha
<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.
这就是所有的人。
回答by Jquestions
Create a rule https://laravel.com/docs/5.7/validation#custom-validation-rules
创建规则 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()]
));