Google recaptcha validation with Jquery

Google recaptcha validation with Jquery

本文关键字:Jquery with validation recaptcha Google      更新时间:2023-09-26

我有兴趣在用户勾选并验证谷歌验证码时隐藏结果验证码消息。只有第一部分(v.length== 0)有效。else if不起作用。您可以在这里查看表单:https://csandreas1.herokuapp.com

if(grecaptcha.getResponse() == 0) // this works
    {
        $('#resultcaptcha').show();
        $('#resultcaptcha').html('<i class="fa fa-exclamation-circle w3-text-red fa-3x" aria-hidden="true"></i> <span class="w3-text-white w3-bold" style="font-size:16px"> Please verify that you are a human</span>');
    }
    else if(grecaptcha.getResponse() == 1)//this doesn't work
    {
        $('#resultcaptcha').hide();
        $('#resultcaptcha').html('');
    }
    else{//submit the form}

以上代码位于表单submit事件处理程序中,只有当点击"submit" (SEND)按钮时才会触发。

要在验证验证后立即隐藏错误消息,您需要在captcha元素(class="g-recaptcha")上使用data-callback,顾名思义,它提供了在验证验证成功时执行的回调。这是文档链接。

代码应该是这样的。(我无法验证代码与data-callback属性,但它确实工作与grecaptcha.render()方法)

<script>
     function captcha_callback(response) {
        if (response.length > 1) {
            $('#resultcaptcha').html('');
        }
    }
</script>
<div class="g-recaptcha" data-sitekey="site_key" data-callback="captcha_callback"><div>

同样,如果你想再次重置验证码,比如在成功提交后清除表单,你可以使用:(见文档)

grecaptcha.reset()