如何使用javascript/jQuery验证谷歌再验证v2 ?

时间:2023-01-17 13:30:32

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 cmdSubmit click.

我想在cmdSubmit单击上验证验证验证验证码。

Please help.

请帮助。

11 个解决方案

#1


84  

Client side verification of reCaptcha - the following worked for me :

reCaptcha的客户端验证—以下对我有用:

" grecaptcha.getResponse(); " returns a null if reCaptcha is not validated on client side, else is returns a value other than null.

“grecaptcha.getResponse();如果在客户端未验证验证,则返回null,否则返回值为null。

Javascript Code :

Javascript代码:

var response = grecaptcha.getResponse();

if(response.length == 0)
    //reCaptcha not verified

else
    //reCaptch verified

#2


62  

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; 
    }
}

#3


23  

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 :

所有这些都来自于谷歌API注释:

Google Recaptcha v2 API Notes

谷歌再验证v2 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字段和您的私钥,以安全地验证服务器端。除非您想要禁用submit按钮,直到recaptcha成功了——在这种情况下,上面的方法应该是有效的。

Hope this helps.

希望这个有帮助。

Paul

保罗

#4


21  

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);
    };

#5


10  

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.

我使用了HarveyEV的解决方案,但是读错了,使用了jQuery validate而不是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>

#6


5  

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()”方法验证recaptcha,如下所示。

 <script type="text/javascript">
     function IsRecapchaValid()
      {
      var res = grecaptcha.getResponse(widId);
      if (res == "" || res == undefined || res.length == 0)
         {
          return false;
         }
       return true;
      }
 </script>

#7


3  

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"/>

#8


1  

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;
           }
       });

#9


1  

The Google reCAPTCHA version 2 ASP.Net allows validating the Captcha response on the client side using its Callback functions. In this example, the Google new reCAPTCHA will be validated using ASP.Net RequiredField Validator.

谷歌重新验证了版本2 ASP。Net允许使用其回调函数在客户端验证Captcha响应。在本例中,将使用ASP对谷歌新reCAPTCHA进行验证。净RequiredField验证器。

<script type="text/javascript">
    var onloadCallback = function () {
        grecaptcha.render('dvCaptcha', {
            'sitekey': '<%=ReCaptcha_Key %>',
            'callback': function (response) {
                $.ajax({
                    type: "POST",
                    url: "Demo.aspx/VerifyCaptcha",
                    data: "{response: '" + response + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var captchaResponse = jQuery.parseJSON(r.d);
                        if (captchaResponse.success) {
                            $("[id*=txtCaptcha]").val(captchaResponse.success);
                            $("[id*=rfvCaptcha]").hide();
                        } else {
                            $("[id*=txtCaptcha]").val("");
                            $("[id*=rfvCaptcha]").show();
                            var error = captchaResponse["error-codes"][0];
                            $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
                        }
                    }
                });
            }
        });
    };
</script>


    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
    <asp:RequiredFieldValidator ID="rfvCaptcha" ErrorMessage="The CAPTCHA field is required." ControlToValidate="txtCaptcha"
        runat="server" ForeColor="Red" Display="Dynamic" />

    <br />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />

#10


0  

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.

验证码验证是必须的。

#11


0  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script type="text/javascript">
        function get_action() {
            var v = grecaptcha.getResponse();
            console.log("Resp" + v);
            if (v == '') {
                document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
                return false;
            }
            else {
                document.getElementById('captcha').innerHTML = "Captcha completed";
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return get_action();">
    <div>
    <div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
    </div>
   <%-- <input type="submit" value="Button" />--%>
   <asp:Button ID="Button1" runat="server"
       Text="Button" />
    <div id="captcha"></div>
    </form>
</body>
</html>

It will work as expected.

它将像预期的那样工作。

#1


84  

Client side verification of reCaptcha - the following worked for me :

reCaptcha的客户端验证—以下对我有用:

" grecaptcha.getResponse(); " returns a null if reCaptcha is not validated on client side, else is returns a value other than null.

“grecaptcha.getResponse();如果在客户端未验证验证,则返回null,否则返回值为null。

Javascript Code :

Javascript代码:

var response = grecaptcha.getResponse();

if(response.length == 0)
    //reCaptcha not verified

else
    //reCaptch verified

#2


62  

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; 
    }
}

#3


23  

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 :

所有这些都来自于谷歌API注释:

Google Recaptcha v2 API Notes

谷歌再验证v2 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字段和您的私钥,以安全地验证服务器端。除非您想要禁用submit按钮,直到recaptcha成功了——在这种情况下,上面的方法应该是有效的。

Hope this helps.

希望这个有帮助。

Paul

保罗

#4


21  

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);
    };

#5


10  

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.

我使用了HarveyEV的解决方案,但是读错了,使用了jQuery validate而不是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>

#6


5  

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()”方法验证recaptcha,如下所示。

 <script type="text/javascript">
     function IsRecapchaValid()
      {
      var res = grecaptcha.getResponse(widId);
      if (res == "" || res == undefined || res.length == 0)
         {
          return false;
         }
       return true;
      }
 </script>

#7


3  

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"/>

#8


1  

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;
           }
       });

#9


1  

The Google reCAPTCHA version 2 ASP.Net allows validating the Captcha response on the client side using its Callback functions. In this example, the Google new reCAPTCHA will be validated using ASP.Net RequiredField Validator.

谷歌重新验证了版本2 ASP。Net允许使用其回调函数在客户端验证Captcha响应。在本例中,将使用ASP对谷歌新reCAPTCHA进行验证。净RequiredField验证器。

<script type="text/javascript">
    var onloadCallback = function () {
        grecaptcha.render('dvCaptcha', {
            'sitekey': '<%=ReCaptcha_Key %>',
            'callback': function (response) {
                $.ajax({
                    type: "POST",
                    url: "Demo.aspx/VerifyCaptcha",
                    data: "{response: '" + response + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var captchaResponse = jQuery.parseJSON(r.d);
                        if (captchaResponse.success) {
                            $("[id*=txtCaptcha]").val(captchaResponse.success);
                            $("[id*=rfvCaptcha]").hide();
                        } else {
                            $("[id*=txtCaptcha]").val("");
                            $("[id*=rfvCaptcha]").show();
                            var error = captchaResponse["error-codes"][0];
                            $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
                        }
                    }
                });
            }
        });
    };
</script>


    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
    <asp:RequiredFieldValidator ID="rfvCaptcha" ErrorMessage="The CAPTCHA field is required." ControlToValidate="txtCaptcha"
        runat="server" ForeColor="Red" Display="Dynamic" />

    <br />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />

#10


0  

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.

验证码验证是必须的。

#11


0  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script type="text/javascript">
        function get_action() {
            var v = grecaptcha.getResponse();
            console.log("Resp" + v);
            if (v == '') {
                document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
                return false;
            }
            else {
                document.getElementById('captcha').innerHTML = "Captcha completed";
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return get_action();">
    <div>
    <div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
    </div>
   <%-- <input type="submit" value="Button" />--%>
   <asp:Button ID="Button1" runat="server"
       Text="Button" />
    <div id="captcha"></div>
    </form>
</body>
</html>

It will work as expected.

它将像预期的那样工作。