Require attribute on the input field doesn't work when i implement google recaptcha. When the input is empty, the form is supposed not to be submitted. But the form gets submitted when input is empty. I followed google's guide to implement that in its simplest form.
<?php if (isset($_POST['code']) && ($_POST['code'] == "whatever")) //do stuff?> ?>
What i want to do is to make the recaptcha execute only when the input is not empty, else prevent form submit and recaptcha execution.
<form id="form1" method="post" > <input name="code" type="text" required> <button data-sitekey="xxx" data-callback='onSubmit' type="submit" class="g-recaptcha" >Let me in</button> </form> </div> <script> function onSubmit(token) { document.getElementById("form1").submit(); } </script> <script src="https://www.google.com/recaptcha/api.js" async defer></script>
I know the question is 5 years old, but it's something that still happens and I'd like to share the most practical solution possible
Google's instructions are as follows:
<!-- In your form, change your submit button -->
<button class="g-recaptcha"
data-sitekey="PUT_YOUR_reCAPTCHA_SITE_KEY"
data-callback='onSubmit'
data-action='submit'>Submit</button>
<!-- Include the recaptcha api.js and create the onSubmit function -->
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("YOUR_FORM_ID").submit();
}
</script>
In this way, you will lose the validation of the inputs, because the javascript function will bypass it.
But you can invoke the html validation directly by the javascript function as follows:
<script>
function onSubmit(token) {
var form = document.getElementById("YOUR_FORM_ID");
if (form.checkValidity()) {
form.submit();
} else {
grecaptcha.reset();
form.reportValidity();
}
}
</script>
This way, html validation will continue to occur and display indications of mandatory fields. The form will only be sent if all mandatory fields are filled in correctly (form validated).
Credits: @brandonaaron
Looking over the documentation you linked to, you are probably better off getting rid of the required
attribute and adding a check to your script to not submit the form if the I put field is null.
So JavaScript would be checking if the field is empty and then give a validation alert or however works best for your situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With