我搜索并无法弄清楚如何 validate the new reCaptcha , 在表单提交之前,以及 jQuery validation Plugin 的验证功能.
我的意图:
$.validator.addMethod('reCaptchaMethod', function (value, element, param) {
if (grecaptcha.getResponse() == ''){
return false;
} else {
// I would like also to check server side if the recaptcha response is good
return true
}
}, 'You must complete the antispam verification');
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
reCaptcha: {
reCaptchaMethod: true
}
},
messages: {
name: "Please fill your name",
email: "Please use a valid email address"
},
submitHandler : function () {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
简而言之:我想检查服务器端,使用 remote method , 如果用户在提交表单之前通过了 recaptcha 验证,以及其他验证规则。
我能够检查recaptcha AFTER 提交(在sendmail.php 上),但最好将recaptcha 验证响应与其他字段验证一起进行。
主要原因是为了更好的用户体验,同时检查所有字段。
我已经成功实现了这一点,将检查移到了 submitHandler 中:
submitHandler : function () {
if (grecaptcha.getResponse() == ''){
// if error I post a message in a div
$( '#reCaptchaError' ).html( '<p>Please verify youare human</p>' );
} else {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
}
但我不喜欢这种方法,原因有两个:
- 它只是检查recaptcha是否已填写,而不是它是否有效,并且
- 用户感觉这是一个两步验证。
In this answer他们说可以在回调中呈现 Recaptcha,以在成功的 CAPTCHA 响应上指定函数调用。
我试图实现它,但我无法在 validate() 函数的规则中使用此解决方案。
最佳答案
我知道这个问题有点过时了,但我遇到了同样的问题并且刚刚找到了解决方案。 您可以通过在 reCaptcha div 旁边添加一个隐藏字段来执行此操作,例如:
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
然后在你的 javascript 中:
$("#form").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},(...rest of your code)
注意您必须在您的代码中使用 ignore: ".ignore"
因为 jquery.validate 默认忽略隐藏字段,而不是验证它们。
如果你想删除 reCapcha 验证时的错误消息,请向 reCapcha 元素添加数据回调
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}" data-callback="recaptchaCallback"></div>
然后在你的js文件中添加
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
关于javascript - 带有 jQuery 验证插件的新 reCaptcha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29563822/