jQuery验证动态创建的reCaptcha表单

时间:2019-03-20 12:01:45

标签: jquery jquery-validate recaptcha invisible-recaptcha

我正在使用以下表单进行验证:

$(document).ready(function() {
    $('form.brochure_form').validate();
});

我目前正在使用它动态创建不可见的Recaptcha(这种方法无需验证即可使用。)

function onloadCallback() {
    var count = 1;

    $(".g-recaptcha").each(function() {
        var object = $(this);
        var theid = object.attr('id');      
        var widgetID = "recaptcha_" + count;
        grecaptcha.render("recaptcha_" + count, {
            "sitekey" : "SITEKEY",
            "callback" : function(token) {


                object.parents('form').find(".g-recaptcha-response").val(token);

                // VALIDATE HERE
                if(object.parents('form').valid() == true){
                    object.parents('form').submit();
                } else {
                    grecaptcha.reset(widgetID);

                };
            }
        });
        count++;

    });
}

这是目前的工作方式;

  1. 表单使用reCaptcha进行验证
  2. 表单运行jQuery验证
  3. 提交

问题是,如果表单验证#1,然后在#2上失败,则我需要重置reCaptcha才能再次执行此操作(这是我在努力的原因,因为我无法正确传递widgetID-如果将其保留为空白,则可以正常工作仅限第一种形式)

我的理想情况是切换#1和#2,但我也无法正常工作。

此外,以上内容当前返回

Uncaught (in promise) null

这里有HTML供参考(因为它是一个很大的表格,所以删除了所有字段)

<form id="form--brochure1" class="brochure_form " action="" method="post">
    <input type="submit" value="Submit" class="g-recaptcha" id="recaptcha_1" data-badge="inline">
</form>

<form id="form--brochure2" class="brochure_form " action="" method="post">
    <input type="submit" value="Submit" class="g-recaptcha" id="recaptcha_2" data-badge="inline">
</form>

该页面仅在提交时刷新,但我正在按以下方式进行服务器端验证:

if(isset($_POST['g-recaptcha-response'])) {

$secretKey = 'SECRETKEY';
$response = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];

$reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp");
$result = json_decode($reCaptchaValidationUrl, TRUE);


  if($result['success'] == 1) {
     // EMAIL SENT, DATABASE UPDATED ETC HERE
   }
}

0 个答案:

没有答案