Search code examples
c#asp.net-coreasp.net-core-mvcrecaptcharecaptcha-v3

Inside my asp.net core MVC web application how i can make the recaptcha a required field


I am working on an asp.net core mvc web application, and i have added the following field to show google recaptcha version 2:-

<div class="form-group">
      <div class="col-md-2"></div>
            <div class="col-md-10">
                <div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="@ViewData["ReCaptchaKey"]">
            </div>
      </div>
 </div>
 //code goes here
 @section Scripts {

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

and inside my action method i am checking if the user select the recaptcha or not, as follow:-

public async Task<IActionResult> SearchNPI(ContactinfoCreate ci)
        {

            //add uncompleted entry
            ViewData["ReCaptchaKey"] = _configuration.GetSection("GoogleReCaptcha:key").Value;
            if (!ReCaptchaPassed(
            Request.Form["g-recaptcha-response"], // that's how you get it from the Request object
            _configuration.GetSection("GoogleReCaptcha:secret").Value,
            _logger
            ))
            {
                ModelState.AddModelError(string.Empty, "Please enter CAPTCHA");
                
            }

but on the client side how i can ake the recaptcha required filed, so the user can not submit the form unless he/she select the recaptcha?


Solution

  • You can determine whether clicks recaptcha before submit by triggering the data-callback method of recaptcha, and then adding a hidden control.

    After clicking recaptcha,assign a value to hidden control in data-callback method, and then judge the hidden value in the form submit method to determine whether this form can be submitted.

    <form method="post"> 
        <div class="form-group">
            <div class="col-md-2"></div>
            <div class="col-md-10">
                <div class="g-recaptcha" data-sitekey="@ViewData["ReCaptchaKey"]" data-callback="recaptchaCallback"></div> 
                <input type="hidden"  value="" id="isClickCaptcha" />
                <span class="text-danger" id="validationText"></span>
            </div> 
        </div>
        <input id="Submit1" type="submit" value="submit" />
    </form>
    <script src="https://www.google.com/recaptcha/api.js?hl=en-US"></script>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script>
        var recaptchaCallback = function () { 
            $("#isClickCaptcha").val("yes");
        };
    
        $("form").submit(function () {
            if ($("#isClickCaptcha").val() == "") {
                event.preventDefault();
                $("#validationText").text("Please enter CAPTCHA!");
                return false;
            }
    
        })
    </script>
    

    Here is the test result: enter image description here