Require User to click google's new recaptcha before form submission

China☆狼群 提交于 2019-12-03 17:30:47

问题


I am using google's new recaptcha inside my form (HTML5): https://www.google.com/recaptcha

Is there a way to check and mark recaptcha as required before form submission? I want to validate this on client side instead of server side. That way, I don't have to go back to the form and warn user about not entering anything for the captcha.

Any javascript that I can use to check whether user enter anything in recaptcha?


回答1:


You can check the textarea field with id g-recaptcha-response. You can do as following:

$("form").submit(function(event) {

   var recaptcha = $("#g-recaptcha-response").val();
   if (recaptcha === "") {
      event.preventDefault();
      alert("Please check the recaptcha");
   }
});

Hope this helps you.




回答2:


A vanilla JavaScript implementation using parts of both Ankesh's and Lammert's solution:

var form = document.getElementById('ctct-custom-form');
form.addEventListener("submit", function(event){
    if (grecaptcha.getResponse() === '') {                            
      event.preventDefault();
      alert('Please check the recaptcha');
    }
  }
, false);

Credit to for form submit listener code: How can I listen to the form submit event in javascript?




回答3:


grecaptcha.getResponse() - Returns the response for the Recaptcha. You can check this in condition such as

grecaptcha.getResponse(opt_widget_id) === ""

Optional widget ID, defaults to the first widget created if unspecified.

Ref: https://developers.google.com/recaptcha/docs/display




回答4:


I tried to improve rylanb's answer. The code below find all the forms in the page that have g-captcha activated and prevent from submission. Note: It assumes that your div.g-recaptcha is the child of form

var forms = document.querySelectorAll('div.g-recaptcha');
forms.forEach(element => {
    element.parentElement.addEventListener("submit", function(event) {
        if (grecaptcha.getResponse() === '') {
            event.preventDefault();
            alert('Please check the recaptcha');
        }
    }, false)
});


来源:https://stackoverflow.com/questions/31017261/require-user-to-click-googles-new-recaptcha-before-form-submission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!