To validate Google reCAPTCHA on form submission, you need to follow several steps to ensure that the reCAPTCHA response from the user is verified on your server.
data-sitekey: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI using for local server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form with reCAPTCHA</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<style>
.error {
color: red;
font-size: 0.875em;
}
</style>
</head>
<body>
<form id="myForm" action="22.php">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label class="error" for="name"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label class="error" for="email"></label>
</div>
<div class="form-group">
<!-- <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div> -->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<label class="error" for="g-recaptcha-response"></label>
</div>
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function () {
$('#myForm').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Your name must consist of at least 2 characters"
},
email: {
required: "Please enter your email",
email: "Please enter a valid email address"
}
},
errorPlacement: function (error, element) {
// Place error message next to the invalid field
if (element.attr("name") === "g-recaptcha-response") {
error.insertAfter(".g-recaptcha");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
// Get reCAPTCHA response
var response = grecaptcha.getResponse();
if (response.length === 0) {
// Add a custom error message for reCAPTCHA
$(".g-recaptcha").after('<label class="error" for="g-recaptcha-response">Please verify that you are not a robot.</label>');
return false;
}
// If reCAPTCHA is validated, submit the form
form.submit();
}
});
});
</script>
</body>
</html>