[javascript] How can I validate google reCAPTCHA v2 using javascript/jQuery?

I have a simple contact form in aspx. I want to validate the reCaptcha (client-side) before submitting the form. Please help.

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.

Please help.

This question is related to javascript jquery asp.net google-api recaptcha

The answer is


Simplified Paul's answer:

Source:

<script src="https://www.google.com/recaptcha/api.js"></script>

HTML:

<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>

JS:

var correctCaptcha = function(response) {
        alert(response);
    };

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:

        $('#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;
           }
       });

Unfortunately, there's no way to validate the captcha on the client-side only (web browser), because the nature of captcha itself requires at least two actors (sides) to complete the process. The client-side - asks a human to solve some puzzle, math equitation, text recognition, and the response is being encoded by an algorithm alongside with some metadata like captcha solving timestamp, pseudo-random challenge code. Once the client-side submits the form with a captcha response code, the server-side needs to validate this captcha response code with a predefined set of rules, ie. if captcha solved within 5 min period, if the client's IP addresses are the same and so on. This a very general description, how captchas works, every single implementation (like Google's ReCaptcha, some basic math equitation solving self-made captchas), but the only one thing is common - client-side (web browser) captures users' response and server-side (webserver) validates this response in order to know if the form submission was made by a human or a robot.

NB. The client (web browser) has an option to disable the execution of JavaScript code, which means that the proposed solutions are completely useless.


<%@ 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.


If you render the Recaptcha on a callback

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>

using an empty DIV as a placeholder

<div id='html_element'></div>

then you can specify an optional function call on a successful CAPTCHA response

var onloadCallback = function() {
    grecaptcha.render('html_element', {
      'sitekey' : 'your_site_key',
      'callback' : correctCaptcha
    });
  };

The recaptcha response will then be sent to the 'correctCaptcha' function.

var correctCaptcha = function(response) {
    alert(response);
};

All of this was from the Google API notes :

Google Recaptcha v2 API Notes

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.

Hope this helps.

Paul


Use this to validate google captcha with simple javascript.

This code at the html body:

<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:

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

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

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

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

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

Javascript Code:

var response = grecaptcha.getResponse();

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

else
    //reCaptch verified

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.

 let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
    'callback': function(response) {
        recaptchVerified = true;
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        // ...
    },
    'expired-callback': function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
    }
});

Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.

So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.


_x000D_
_x000D_
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {_x000D_
                dvcontainer = grecaptcha.render('dvCaptcha', {_x000D_
                    'sitekey': ReCaptchSiteKey,_x000D_
                    'expired-callback' :function (response){_x000D_
                        recaptch.reset();_x000D_
                        c_responce = null;_x000D_
                    },_x000D_
                    'callback': function (response) {_x000D_
                        $("[id*=txtCaptcha]").val(c_responce);_x000D_
                        $("[id*=rfvCaptcha]").hide();_x000D_
                        c_responce = response;_x000D_
_x000D_
                    }_x000D_
                });_x000D_
            }_x000D_
            _x000D_
            function callonanybuttonClick(){_x000D_
             _x000D_
                if (c_responce == null) {_x000D_
                    $("[id*=txtCaptcha]").val("");_x000D_
                    $("[id*=rfvCaptcha]").show();_x000D_
_x000D_
                    return false;_x000D_
                }_x000D_
                else {_x000D_
                    $("[id*=txtCaptcha]").val(c_responce);_x000D_
                    $("[id*=rfvCaptcha]").hide();_x000D_
                    return true;_x000D_
                }_x000D_
            _x000D_
}
_x000D_
<div id="dvCaptcha" class="captchdiv"></div>_x000D_
    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />_x000D_
    <label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
_x000D_
_x000D_
_x000D_

Captcha validation is required.


Here's how we were able to validate the RECAPTCHA using .NET:

FRONT-END

<div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>

BACK-END:

    public static bool IsCaptchaValid(HttpRequestBase requestBase)
    {
        var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
        if (string.IsNullOrEmpty(recaptchaResponse))
        {
            return false;
        }

        string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
        byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = "";

        using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
        {
            responseString = sr.ReadToEnd();
        }

        return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
    }

Call the above method within your Controller's POST action.


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.

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

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.

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

Source Link

enter image description here

You can simply check on client side using grecaptcha.getResponse() method

          var rcres = grecaptcha.getResponse();
          if(rcres.length){
            grecaptcha.reset();
            showHideMsg("Form Submitted!","success");
          }else{
            showHideMsg("Please verify reCAPTCHA","error");
          }

you can render your recaptcha using following code

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to google-api

Google API authentication: Not valid origin for the client Using Postman to access OAuth 2.0 Google APIs How can I validate google reCAPTCHA v2 using javascript/jQuery? This IP, site or mobile application is not authorized to use this API key Is there a Google Keep API? OAuth2 and Google API: access token expiration time? invalid_grant trying to get oAuth token from google Alternative to google finance api How do I access (read, write) Google Sheets spreadsheets with Python? How to refresh token with Google API client?

Examples related to recaptcha

Google Recaptcha v3 example demo How to hide the Google Invisible reCAPTCHA badge reCAPTCHA ERROR: Invalid domain for site key How can I validate google reCAPTCHA v2 using javascript/jQuery? ReCaptcha API v2 Styling Change New Google Recaptcha (v2) Width How to Validate Google reCaptcha on Form Submit Google reCAPTCHA: How to get user response and validate in the server side? How does Google reCAPTCHA v2 work behind the scenes? How to validate Google reCAPTCHA v3 on server side?