2

I am trying to implement the new Google Invisible Recaptcha and for some reason yet unknown to me the automatic html form validation and the required attributes does not seem to be working after along with the Recaptcha. I am guessing it is because of the onSubmit() function callback. Can someone let me know how to fix this issue? Thanks in advance.

Below is my implementation of a form with Google Invisible Recaptcha. The data-sitekey has been intentionally removed.

<html>
<head>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  <script>
    function onSubmit(token) {
      document.getElementById("contactForm").submit();
    }
  </script>
</head>
<body>
<form id="contactForm" action="#" method="POST">
  <p>Leave a Message</p>
  <label for="inputName">Name</label>
  <input type="text" name="Name" id="inputName" placeholder="Name" required> <br>
  <label for="inputEmail">Email</label>
  <input type="email" name="Email" id="inputEmail" placeholder="Email Id" required> <br>
  <label for="inputMessage">Message</label>
  <input type="text" name="Message" id="inputMessage" placeholder="Message" required><br/>
  <button class="g-recaptcha" type="submit" data-sitekey="//site-key" data-badge="bottomleft" data-callback='onSubmit'>Submit</button>
  <button type="reset">Reset</button>
</form>
</body>
</html>

3
  • are you sure use site key and secret confirm??
    – A.A Noman
    Commented Apr 10, 2017 at 5:00
  • Yes I have used the right site key and secret key. This is not my first time using Google Captcha's. Encountered this problem when I was trying to use their new v2 Invisible Captcha. Commented Apr 11, 2017 at 5:25
  • Need to invoke grecaptcha.execute() method. Try this example Commented Jun 2, 2018 at 8:17

2 Answers 2

1

Create a callback function which sets the onclick property of the submit button to onSubmit function and then triggers a click.

 <script>
 function callBack(){
  document.getElementById('submit-button').addEventListener('click',onSubmit);
  document.getElementById('submit-button').click();
 }

 function onSubmit() {
 //validation code here
  document.getElementById("contactForm").submit();
 }
</script>

Set this callback function to the data-callback property

<button id='submit-button' class="g-recaptcha" type="submit" data-sitekey="//site-key" data-badge="bottomleft" data-callback='callBack'>Submit</button>
1
  • 3
    This doesn't trigger html validation. This only gives you an area to inject your own javascript validation.
    – sfxworks
    Commented Apr 5, 2018 at 1:37
0

You have to do it programmatically thanks to a new v2 grecaptcha method: grecaptcha.execute() so that recaptcha doesn't replace the button's default click event which was preventing the default HTML5 form validation.

See this answer from HTML5 form validation before reCAPTCHA's.

Not the answer you're looking for? Browse other questions tagged or ask your own question.