I had the same problem as yours and solved it this way:
First declare a variable that stores 1
or 0
depending or whether the user filled the capcha correctly.
var allowSubmit = false;
Then you need a function which gets executed when the user fills the reCapcha correctly:
function capcha_filled () {
allowSubmit = true;
}
... and a function that gets executed when the reCapcha session expires:
function capcha_expired () {
allowSubmit = false;
}
To tell reCapcha about your functions (callbacks), set those data-
attributes in your html:
<div class="g-recaptcha"
data-callback="capcha_filled"
data-expired-callback="capcha_expired"
data-sitekey="your site key"></div>
Or if you use explicit load:
var onloadCallback = function() {
grecaptcha.render('your_div_id', {
'sitekey' : 'your_site_key',
'callback': capcha_filled,
'expired-callback': capcha_expired,
});
};
You need also a callback for the form submission:
function check_if_capcha_is_filled (e) {
if(allowSubmit) return true;
e.preventDefault();
alert('Fill in the capcha!');
}
Finally add in the form the onsubmit
attribute:
<form action="..." onsubmit="check_if_capcha_is_filled">
Note: as mentioned in the comments, a server validation is still needed. The code prevents accidentally submitting the form unless the capcha is filled and is only for user's convenience.