Search code examples
javascriptjqueryasp.net-core-mvcrecaptcha-v3

How to remove a validation error beside captcha if the user select the captcha


I am working on an asp.net MVC core web application, and i added a captcha as follow:-

<div class="form-group">
                        <div class="col-md-2"></div>
                        <div class="col-md-10">
                            <span class="msg-error error"></span>
                            <div id="recaptcha" class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="@ViewData["ReCaptchaKey"]"></div>
                        </div>
                    </div>

also i added the following javascript validation to force a required on the captcha:-

$('#getmyestimate').click(function () {
               
                var $captcha = $('#recaptcha'),
                    response = grecaptcha.getResponse();

                if (response.length === 0) {
                    $('.msg-error').text("reCAPTCHA is mandatory");
                    if (!$captcha.hasClass("error")) {
                        $captcha.addClass("error");
                    }
                } else {
                    $('.msg-error').text('');
                    $captcha.removeClass("error");
                    alert('reCAPTCHA marked');
                }
            })

as follow:-

enter image description here

but what i am trying to do , is that once the user select the captcha to remove the validation error (if any),, so can anyone advice how i can do so?


Solution

  • You can hide inside your callback recaptchaCallback function that you have already added in data-callback attribute in the g-recaptcha class.

    var recaptchaCallback = function() {
       $('#recaptcha').removeClass("error");
       ... //Any other code in the callback
    }