2017-03-07 52 views
1

我想在form中使用recaptcha,但是,我無法將其設置爲required。我試圖使用this問題的前兩個答案的代碼,但是,他們都沒有工作。reCaptcha字段按要求

這裏是我的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> 

回答

4

function validateForm() { \t 
 
    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>

+1

你'validateForm( )'函數與jQ完全無關uery驗證插件。該插件會自動將驗證消息插入表單中,並且您的自定義功能會彈出瀏覽器「警報」。 – Sparky