如何使用 javascript/jQuery 验证 google reCAPTCHA v2?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27902539/
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
How can I validate google reCAPTCHA v2 using javascript/jQuery?
提问by Mahatma Aladdin
I have a simple contact form in aspx. I want to validate the reCaptcha (client-side) before submitting the form. Please help.
我在aspx中有一个简单的联系表格。我想在提交表单之前验证 reCaptcha(客户端)。请帮忙。
Sample code:
示例代码:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Form</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
$("#cmdSubmit").click(function () {
//need to validate the captcha
});
</script>
</head>
<body>
<form id="form1" runat="server">
<label class="clsLabe">First Name<sup>*</sup></label><br />
<input type="text" id="txtFName" name="txtFName" class="clsInput" /><br />
<div class="g-recaptcha" data-sitekey="my_key"></div>
<img id="cmdSubmit" src="SubmitBtn.png" alt="Submit Form" style="cursor:pointer;" />
</form>
</body>
</html>
I want to validate the captcha on cmdSubmitclick.
我想在cmdSubmit点击时验证验证码。
Please help.
请帮忙。
回答by Palak Tanejaa
This Client side verification of reCaptcha- the following worked for me :
这个客户端验证reCaptcha- 以下对我有用:
if reCaptcha is not validated on client side grecaptcha.getResponse();returns null, else is returns a value other than null.
如果在客户端grecaptcha.getResponse();返回时未验证 reCaptcha null,则返回null.
Javascript Code:
Javascript代码:
var response = grecaptcha.getResponse();
if(response.length == 0)
//reCaptcha not verified
else
//reCaptch verified
回答by Pravin Sharma
Use this to validate google captcha with simple javascript.
使用它通过简单的 javascript 验证谷歌验证码。
This code at the html body:
html正文中的此代码:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
此代码放在调用 get_action(this) 方法表单按钮的 head 部分:
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
回答by Manuel Azar
Simplified Paul's answer:
简化保罗的回答:
Source:
来源:
<script src="https://www.google.com/recaptcha/api.js"></script>
HTML:
HTML:
<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>
JS:
JS:
var correctCaptcha = function(response) {
alert(response);
};
回答by pphillips001
If you render the Recaptcha on a callback
如果您在回调中呈现 Recaptcha
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
using an empty DIV as a placeholder
使用空的 DIV 作为占位符
<div id='html_element'></div>
then you can specify an optional function call on a successful CAPTCHA response
然后您可以在成功的 CAPTCHA 响应上指定一个可选的函数调用
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback' : correctCaptcha
});
};
The recaptcha response will then be sent to the 'correctCaptcha' function.
然后,recaptcha 响应将发送到“correctCaptcha”功能。
var correctCaptcha = function(response) {
alert(response);
};
All of this was from the Google API notes :
所有这些都来自 Google API 说明:
I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.
我有点不确定你为什么要这样做。通常,您会将 g-recaptcha-response 字段与您的私钥一起发送,以安全地验证服务器端。除非您想在 recaptcha 成功或类似情况下禁用提交按钮 - 在这种情况下,上述方法应该有效。
Hope this helps.
希望这可以帮助。
Paul
保罗
回答by imjosh
I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.
我使用了 HarveyEV 的解决方案,但误读了它并使用 jQuery 验证而不是 Bootstrap 验证器来完成它。
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script>
$("#contactForm").validate({
submitHandler: function (form) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if (response.length == 0) {
$('#recaptcha-error').show();
return false;
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
return true;
}
}
});
</script>
回答by BV2005
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
我认为它们都很棒,但实际上让它们使用 javascript 和 c# 时遇到了麻烦。这是我所做的。希望它可以帮助别人。
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
回答by Tabish Usman
you can render your recaptcha using following code
您可以使用以下代码呈现您的recaptcha
<div id="recapchaWidget" class="g-recaptcha"></div>
<script type="text/javascript">
var widId = "";
var onloadCallback = function ()
{
widId = grecaptcha.render('recapchaWidget', {
'sitekey':'Your Site Key'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Then you can validate your recaptcha by using "IsRecapchaValid()" method as follows.
然后,您可以使用“IsRecapchaValid()”方法来验证您的验证码,如下所示。
<script type="text/javascript">
function IsRecapchaValid()
{
var res = grecaptcha.getResponse(widId);
if (res == "" || res == undefined || res.length == 0)
{
return false;
}
return true;
}
</script>
回答by HarveyEV
I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:
我在 Bootstrap 验证器中使用了 Palek 的解决方案并且它有效。我会向他添加评论,但我没有代表;)。简化版:
$('#form').validator().on('submit', function (e) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if(response.length == 0) {
e.preventDefault();
$('#recaptcha-error').show();
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
}
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});
回答by Code Spy
You can simply check on client side using grecaptcha.getResponse()method
您可以使用grecaptcha.getResponse()方法简单地检查客户端
var rcres = grecaptcha.getResponse();
if(rcres.length){
grecaptcha.reset();
showHideMsg("Form Submitted!","success");
}else{
showHideMsg("Please verify reCAPTCHA","error");
}
回答by Karangiri goswami
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {
dvcontainer = grecaptcha.render('dvCaptcha', {
'sitekey': ReCaptchSiteKey,
'expired-callback' :function (response){
recaptch.reset();
c_responce = null;
},
'callback': function (response) {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
c_responce = response;
}
});
}
function callonanybuttonClick(){
if (c_responce == null) {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
return false;
}
else {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
return true;
}
}
<div id="dvCaptcha" class="captchdiv"></div>
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
Captcha validation is required.
需要验证码验证。


