谷歌ReCAPTCHA如何制作所需?

问题描述 投票:13回答:4

有谁知道如何使Google ReCAPTCHA (v2)中的“form”成为“必需”?

我的意思是在重新填写之前没有表格提交?

我在我的形式中使用ParsleyJs,但没有找到一种方法使它与divs一起使用...

jquery html validation recaptcha parsley.js
4个回答
16
投票

您必须使用reCaptcha验证响应回调。像这样:<script src='https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit'></script>

var RC2KEY = 'sitekey',
    doSubmit = false;

function reCaptchaVerify(response) {
    if (response === document.querySelector('.g-recaptcha-response').value) {
        doSubmit = true;
    }
}

function reCaptchaExpired () {
    /* do something when it expires */
}

function reCaptchaCallback () {
    /* this must be in the global scope for google to get access */
    grecaptcha.render('id', {
        'sitekey': RC2KEY,
        'callback': reCaptchaVerify,
        'expired-callback': reCaptchaExpired
    });
}

document.forms['form-name'].addEventListener('submit',function(e){
    if (doSubmit) {
        /* submit form or do something else */
    }
})

2
投票

对于ParsleyJS,您将做一些解决方法:

1.添加隐藏的输入字段,使用data-parsley-required="true"value = "",如下所示:

<input id="myField" data-parsley-errors-container="#errorContainer" data-parsley-required="true" value="" type="text" style="display:none;">

2.添加错误容器(在g-recaptcha div下方或下方):

<span id='errorContainer'></span>

3.在你的js代码中的某处添加这个简单的函数:

function recaptchaCallback() {
    document.getElementById('myField').value = 'nonEmpty';
}

4.使用自定义函数的值添加属性data-callback

<div class="g-recaptcha" data-sitekey="***" data-callback="recaptchaCallback"></div>

1
投票

你可以在这里找到另一个有效的例子:https://codepen.io/reactionmedia/pen/JVdmbB

在本例中,我将在表单中创建两个HTML元素:

<div id="botvalidator"></div>
<div id="captchaerrors"></div>

botvalidator将包含google recaptcha iframe,其中包含“我不是机器人”复选框。检查用户未单击“我不是机器人”复选框后,captchaerrors将包含错误。

重要提示:我们正在使用arri.js库,以便了解google recaptcha何时在DOM中添加新的g-recaptcha-response textarea元素,因为先前的DOM新节点插入验证不再有效。将recaptcha加载到页面中几分钟后会发生此事件。

您可以从:https://github.com/uzairfarooq/arrive/下载arri.js库

或直接从CDN提供商处插入,例如:https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js

请记住在加载JQUERY库后插入所有库以避免错误。我正在使用Jquery 2.2.4版本

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

另一个重要的事情是要记住以这种方式加载recaptcha库,以便在加载recaptcha后执行onloadCallback函数并“手动”渲染recaptcha

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>

这是代码片段:

var onloadCallback = function() {
        /**
         * If we try to load page to show the congrats message we don't need to load recaptcha.
         */
        if($("#botvalidator").length > 0) {
            grecaptcha.render('botvalidator', {
                'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
                'callback': cleanErrors
            });
            addCaptchaValidation();
            /**
             * We are going to use arrive library in order to check new google recaptcha
             * element added after the current one is expired and then we will create new attributes for that element.
             * Expires-callback google recaptcha is not working, probably it is executed before element creation.
             * https://github.com/uzairfarooq/arrive/
             */
            $(document).arrive("#g-recaptcha-response", function() {
                // 'this' refers to the newly created element
                addCaptchaValidation();
            });
        }
    };

        /**  We are going to remove all errors from the container. */
    var cleanErrors = function() {
        $("#captchaerrors").empty();
    };
    
    var addCaptchaValidation = function() {
        console.log("Adding captcha validation");
        
        cleanErrors();

        $('#myform').parsley().destroy();

        $('#g-recaptcha-response').attr('required', true);
        // We are going to create a new validator on Parsley
        $('#g-recaptcha-response').attr('data-parsley-captcha-validation', true);
        $('#g-recaptcha-response').attr('data-parsley-error-message', "We know it, but we need you to confirm you are not a robot. Thanks.");
        $('#g-recaptcha-response').attr('data-parsley-errors-container', "#captchaerrors");
    $('#myform').parsley();
    };
    

    /** We are going to add a new Parsley validator, this validation is called from
    #g-recaptcha-response after clicking the submit button*/

    window.Parsley.addValidator('captchaValidation', {

            validateString: function(value) {
                if(debug) console.log("Validating captcha", value);
                if(value.length > 0) {
                    return true;
                } else {
                    return false;
                }                    
            },
            messages: {en: 'We know it, but we need you to confirm you are not a robot. Thanks.'}
          });
<html>
<head>
</head>
<body>
<h1>Parsley and Google Recaptcha Example</h1>
<form id="myform">
  Full name
  <input type="text" name="name" id="name" data-parsley-required="true">
  <br/>
<div id="botvalidator"></div>
<div id="captchaerrors"></div><br/>
  <input type="submit" value="Submit Form">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.8.2/parsley.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/arrive/2.4.1/arrive.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
</body>
</html>

这就是所有人。


0
投票

创建一个规则https://laravel.com/docs/5.7/validation#custom-validation-rules

然后在您的控制器中使用它

// validation
$this->validate( $request, array(
    'g_recaptcha_response' => ['required', 'string', new Captcha()]
));
© www.soinside.com 2019 - 2024. All rights reserved.