Hello Friends, Today we are sharing a useful information to make google recaptcha field required. You can try with below sample code to add validation for recaptcha field.
Sample 1 - Pure javascript
<script>
window.onload = function() {
var $recaptcha = document.querySelector('#g-recaptcha-response');
if($recaptcha) {
$recaptcha.setAttribute("required", "required");
}
};
</script>
Sample 2 - With jQuery
<script>
$('form').on('submit', function(e) {
if(grecaptcha.getResponse() == "") {
e.preventDefault();
alert("You can't proceed!");
} else {
alert("Thank you");
}
});
</script>
Sample 3 - With Javascript onLoad function
<script>
window.onload = function() {
var recaptcha = document.forms["FORM_NAME"]["g-recaptcha-response"];
recaptcha.required = true;
recaptcha.oninvalid = function(e) {
// fazer algo, no caso to dando um alert
alert("Por favor complete o captchaba");
}
}
</script>
Sample 4 - With jQuery.Validation
<script>
submitHandler: function (form) {
var $recaptcha = document.querySelector('#g-recaptcha-response');
if($recaptcha) {
$recaptcha.setAttribute("required", "required");
console.log("You can't proceed!");
this.beenSubmitted = false;
}else{
console.log("Proceed!");
}
}
</script>