[英]Using ReCaptcha with jQuery Validate, giving correct response but gives error
我使用的是jQuery validate和我的网站的注册表格,底部是reCaptcha。 这是检查表单是否有错误的脚本(仅编辑为相关部分):
$(document).ready(function() {
jQuery.validator.addMethod("checkCaptcha", function() {
var phpquery = $.ajax({url:"verify.php",
type: "POST",
async: false,
data:{recaptcha_challenge_field:Recaptcha.get_challenge(),recaptcha_response_field:Recaptcha.get_response()},
success:function(resp) {
if (resp == 'false') {
console.dir(resp);
return false;
} else {
console.dir(resp);
return true;
}
}
});
},"");
$('#regForm').validate({
rules:{
recaptcha_response_field:{required:true,checkCaptcha:true}
},
messages:{
recaptcha_response_field:{checkCaptcha:"Your Captcha response was incorrect. Please try again."}
}
});
});
当我输入正确的reCaptcha响应并单击“响应”文本字段中的“提交”或“制表符”时,会发生什么情况,当它最初在控制台中显示为true
,然后立即抛出false
并阻止我提交表单。
当输入了错误的reCaptcha响应时,也会发生错误,如预期那样,它将抛出false
,但是对于我输入的每个字母,它将提交到verify.php
并返回false
。 当我最终完成输入正确的reCaptcha的输入时,它无法识别出该false
,并且仍然返回false
。
即使输入正确的响应,重新加载reCaptcha也会抛出false
。
我知道verify.php
可以正常工作,因为当<form>
具有action="verify.php,"
一切都将正常运行(即,告诉您是否输入了正确的reCaptcha,无论您尝试了多少次)。
我想念什么吗? 有没有更简单,可靠的方法来做到这一点?
在.validate()
使用onkeyup: false
选项。
否则,每次您键入一个字母,它将运行您的checkCaptcha
方法并将不完整的验证码代码发送到服务器。 我相信一旦发送了错误的验证码,它现在已经过期,您将无法再次发送相同的代码。
无论哪种方式,我认为最好不要在该字段完成后才将代码发送到服务器。
$('#regForm').validate({
onkeyup: false,
rules:{
recaptcha_response_field: {
required: true,
checkCaptcha: true
}
},
messages:{
recaptcha_response_field: {
checkCaptcha: "Your Captcha response was incorrect. Please try again."
}
}
});
另外,如果验证码失败,则需要触发刷新以获取新代码。
Recaptcha.reload();
在您的success
回调中,也许...
success:function(resp) {
if (resp == 'false') {
console.dir(resp);
Recaptcha.reload(); // get a new captcha code on failure
return false;
} else {
console.dir(resp);
return true;
}
}
第一个addMethod验证器的问题是关于如何返回true或false的,而第二个则要复杂得多。 我不知道您如何从服务器端处理问题,但是也许这段代码是您所需要的:
http://blog.netgloo.com/2014/06/03/adding-recaptcha-validator-to-jquery-validate/
这对我来说很棒!
好了,终于明白了(尽管可能只是一种解决方法)。 这是新的addMethod
:
jQuery.validator.addMethod("checkCaptcha", function() {
var bfr = false;
var phpquery = $.ajax({url:"verify.php",
type: "POST",
async: false,
data:{recaptcha_challenge_field:Recaptcha.get_challenge(),recaptcha_response_field:Recaptcha.get_response()},
complete:function(resp) {
if(resp.responseText.indexOf("false")>=0){
Recaptcha.reload();
}else{
bfr = true;
}
}
});
if(bfr){
return true;
}
},"");
我还添加了onkeyup:false
, onclick:false
和onfocusout:false
来validate()
。 这似乎可以完成工作。
这是我关于“ 使用AJAX请求验证验证码 ”的想法。
在表单中添加验证码的主要原因是为了验证提交表单的是机器人还是人类。 因此,即使其他字段有错误,成功提交验证码后,我们显然也知道这是人为的。 因此,在验证码字段首次成功之后将其删除是完全可以的(请刷新验证码,直到成功为止)。 然后可以照常处理其他字段。
有异议吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.