Home > Software engineering >  Form validation with Google reCAPTCHA v2 Invisible
Form validation with Google reCAPTCHA v2 Invisible

Time:11-23

I set up the following form with Google reCAPATCHA v2 Invisible according to Google instructions:

<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
    function submitForm() {
        var form = document.getElementById("contact-form");
        form.submit();
    }
</script>

<form id="contact-form" method="post" action="/send">
    <input name="message" required />
    <button type="submit"  data-sitekey="xxx" data-callback="submitForm">
        Send
    </button>
</form>

The problem is that the required attribute is ignored, and the form can be submitted without filling in the field.

I know I could modify the submitForm() function to perform some manual validation (maybe even call form.checkValidity()), but that won't trigger the default browser validation feedback.

How can I make sure that the browser validates the form and that the standard browser feedback is shown when the field is left empty?

CodePudding user response:

Based on CBroe's comment, the code can be amended like this:

<script src="https://www.google.com/recaptcha/api.js"></script>

<form id="contact-form" method="post" action="/send">
    <input name="message" required />
    <button type="submit">
        Send
    </button>
    <div 
         data-sitekey="xxx"
         data-callback="onCaptchaValidated"
         data-size="invisible">
    </div>
</form>

<script>
    var isCaptchaValidated = false;
    var form = document.getElementById("contact-form");

    function onCaptchaValidated() {
        isCaptchaValidated = true;
        form.submit();
    }

    form.addEventListener("submit", function (event) {
        if (!isCaptchaValidated) {
            event.preventDefault();
            grecaptcha.execute();
        }
    });
</script>
  • Related