How can I make reCAPTCHA a required field?

前端 未结 7 1212
闹比i
闹比i 2020-12-01 05:34

I\'m using Google reCAPTCHA and have been able to add the CAPTCHA component to my page inside a form. But when I submit the form there\'s no validation taking place to check

7条回答
  •  有刺的猬
    2020-12-01 05:53

    I had the same problem as yours and solved it this way:

    First declare a variable that stores 1 or 0 depending or whether the user filled the capcha correctly.

    var allowSubmit = false;
    

    Then you need a function which gets executed when the user fills the reCapcha correctly:

    function capcha_filled () {
        allowSubmit = true;
    }
    

    ... and a function that gets executed when the reCapcha session expires:

    function capcha_expired () {
        allowSubmit = false;
    }
    

    To tell reCapcha about your functions (callbacks), set those data-attributes in your html:

    Or if you use explicit load:

      var onloadCallback = function() {
        grecaptcha.render('your_div_id', {
          'sitekey' : 'your_site_key',
          'callback': capcha_filled,
          'expired-callback': capcha_expired,
        });
      };
    

    You need also a callback for the form submission:

    function check_if_capcha_is_filled (e) {
        if(allowSubmit) return true;
        e.preventDefault();
        alert('Fill in the capcha!');
    }
    

    Finally add in the form the onsubmit attribute:


    Note: as mentioned in the comments, a server validation is still needed. The code prevents accidentally submitting the form unless the capcha is filled and is only for user's convenience.

提交回复
热议问题