Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reCaptcha field as required

I am trying to use recaptcha in a form, however, I am having trouble to set it as required. I tried to use the code of the first two answers of this question, however, none of them worked.

Here is my header code:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>

Here is my body code (I tried first the accepted question):

<form action="some-page.php">
    <fieldset>
        <legend>Personal information:</legend>
        First name:<br>
        <input type="text" name="firstname" value="Name" required><br> Last name:<br>
        <input type="text" name="lastname" value="Last Name" required><br><br>
    <div class="g-recaptcha" data-sitekey="xxxx"></div>
        <input type="hidden" name="recaptcha" data-rule-recaptcha="true">
        <input type="submit" value="Submit">
    </fieldset>
</form>

<script>
    $('form').validate({
        ignore: '.no-validation'
    });

    // Add our validation method for reCaptcha: 
    $.validator.addMethod("recaptcha", function(value, element) {
        var grecaptcha = window.grecaptcha || null;
        return !grecaptcha || grecaptcha.getResponse();
    }, "Please fill reCAPTCHA");
</script>
like image 367
mhery Avatar asked Dec 19 '25 00:12

mhery


1 Answers

function validateForm() {	
    var recaptcha = document.forms["myForm"]["g-recaptcha-response"].value;
    if (recaptcha == "") {
        alert("Please fill reCAPTCHA");
        return false;
    }
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>



<form name="myForm" action="login.php"  onsubmit="return validateForm()" method="post">
    <fieldset>
        <legend>Personal information:</legend>
        First name:<br>
        <input type="text" name="firstname" value="Name" required><br> Last name:<br>
        <input type="text" name="lastname" value="Last Name" required><br><br>
    <div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
        <input type="hidden" name="recaptcha" data-rule-recaptcha="true">
        <input type="submit" value="Submit">
    </fieldset>
</form>
like image 147
Rafiqul Islam Avatar answered Dec 20 '25 18:12

Rafiqul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!