Rya*_*ung 13 javascript php forms recaptcha
我在我的表单(HTML5)中使用google的新recaptcha:https: //www.google.com/recaptcha
在表单提交之前,有没有办法在需要时检查并标记recaptcha?我想在客户端而不是服务器端验证这一点.这样,我不必回到表单并警告用户不要为验证码输入任何内容.
我可以用来检查用户是否在recaptcha中输入任何内容的任何javascript?
jag*_*d89 42
您可以使用id检查textarea字段g-recaptcha-response.您可以执行以下操作:
$("form").submit(function(event) {
var recaptcha = $("#g-recaptcha-response").val();
if (recaptcha === "") {
event.preventDefault();
alert("Please check the recaptcha");
}
});
Run Code Online (Sandbox Code Playgroud)
希望这对你有所帮助.
使用Ankesh和Lammert解决方案的一部分的香草JavaScript实现:
var form = document.getElementById('ctct-custom-form');
form.addEventListener("submit", function(event){
if (grecaptcha.getResponse() === '') {
event.preventDefault();
alert('Please check the recaptcha');
}
}
, false);
Run Code Online (Sandbox Code Playgroud)
感谢表单提交侦听器代码:如何在javascript中监听表单提交事件?
小智 5
grecaptcha.getResponse()- 返回对 Recaptcha 的响应。您可以在条件中检查此内容,例如
grecaptcha.getResponse(opt_widget_id) === ""
可选的小部件 ID,如果未指定,则默认为创建的第一个小部件。
参考:https : //developers.google.com/recaptcha/docs/display
2022 年工作解决方案
就我个人而言,我无法让上述任何解决方案与我的验证码一起使用。所以我想我会为那些面临同样问题的人分享我当前的工作解决方案。
我的笔记.js应该彻底解释解决方案。
JavaScript
// By default do not allow form submission.
var allow_submit = false
function captcha_filled () {
/*
* This is called when Google get's the recaptcha response and approves it.
* Setting allow_submit = true will let the form POST as normal.
* */
allow_submit = true
}
function captcha_expired () {
/*
* This is called when Google determines too much time has passed and expires the approval.
* Setting allow_submit = false will prevent the form from being submitted.
* */
allow_submit = false
}
function check_captcha_filled (e) {
console.log('verify-captcha')
/*
* This will be called when the form is submitted.
* If Google determines the captcha is OK, it will have
* called captcha_filled which sets allow_submit = true
* If the captcha has not been filled out, allow_submit
* will still be false.
* We check allow_submit and prevent the form from being submitted
* if the value of allow_submit is false.
* */
// If captcha_filled has not been called, allow_submit will be false.
// In this case, we want to prevent the form from being submitted.
if (!allow_submit) {
// This call prevents the form submission.
// e.preventDefault()
// This alert is temporary - you should replace it with whatever you want
// to do if the captcha has not been filled out.
alert('ERROR: Please verify you are human by filling out the captcha')
return false
}
captcha_expired()
return true
}
Run Code Online (Sandbox Code Playgroud)
超文本标记语言
<form action="post" onsubmit="return check_captcha_filled()">
<!-- form items -->
<div class="g-recaptcha"
data-callback="captcha_filled"
data-expired-callback="captcha_expired"
data-sitekey="your site key">
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27185 次 |
| 最近记录: |