Reputation: 2248
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>
Upvotes: 3
Views: 7915
Reputation: 1646
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>
Upvotes: 8