How to run reCaptcha ONLY if HTML5 validation has passed?

前端 未结 2 1027
南方客
南方客 2020-12-24 13:22

Usually, HTML5 form validation runs before the submit event.

With this

2条回答
  •  我在风中等你
    2020-12-24 13:57

    Instead of attaching the reCAPTCHA attributes to the button directly you have to add them to a div and then use grecaptcha.execute(); on form submit.

    
    
    
        Name: (required) 
        

    When you add the reCAPTCHA attributes to the button as you did, Google simply adds a click listener to the button and executes the reCAPTCHA when the button is clicked. There is no submit listener added. The HTML5 validation is only triggered by a click on a submit button and runs before the submit event. That is why we must make sure that reCAPTCHA runs after the submit event. Apparently the click event, which reCAPTCHA subscribes to, is dealt with before the internal HTML5 validation would get triggered. The validation is also not triggered when you submit a form using submit(). That is just how that function got defined. Because you call the function in your callback, validation gets not triggered. However even if you did not call the submit() function in the callback it seems that reCAPTCHA stops the event from its default behaviour and thus stops validation completely.

    Submit form after reCAPTCHA completion

    If you want to get the form submitted after the reCAPTCHA is completed, you can check for the result of grecaptcha.getResponse().

    
    
    
    Name: (required)

提交回复
热议问题