reCaptcha字段根据需要

时间:2017-03-07 19:54:21

标签: jquery jquery-validate recaptcha

我尝试在recaptcha中使用form,但是,我无法将其设置为required。我试图使用this问题的前两个答案的代码,但是,它们都没有奏效。

这是我的header代码:

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

这是我的body代码(我首先尝试了接受的问题):

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

1 个答案:

答案 0 :(得分:6)

&#13;
&#13;
function validateForm() {	
    var recaptcha = document.forms["myForm"]["g-recaptcha-response"].value;
    if (recaptcha == "") {
        alert("Please fill reCAPTCHA");
        return false;
    }
}
&#13;
<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>
&#13;
&#13;
&#13;