我使用带有the jQuery Validate插件的新reCaptcha。验证插件适用于我的表单但不幸的是它不适用于reCaptcha。我试图让它在下面工作:
HTML:
<div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="XXXXX"></div>
使用Javascript:
recaptcha: {
required: true
}
但它没有奏效。有谁知道如何解决这一问题。我只需要默认此字段是必需的错误消息。
答案 0 :(得分:5)
你应该为reCaptcha添加隐藏的输入,因为jQuery Validation只能验证input / textarea / select:
<div class="g-recaptcha" data-sitekey="XXXXX"></div>
<input type="hidden" name="recaptcha" data-rule-recaptcha="true">
<!--
We set "data-rule-recaptcha" — this will require jQuery Validate
to validate this field using method named "recaptcha"
(which we write below)
-->
然后像这样重写你的JS:
// By default jQuery Validation ignore hidden inputs,
// so we change settings to ignore inputs with class "no-validation".
// Cause our hidden input didn't have this class — it would be validated!
$('form').validate({
ignore: '.no-validation'
});
// Add our validation method for reCaptcha:
$.validator.addMethod("recaptcha", function(value, element) {
var grecaptcha = window.grecaptcha || null;
return !grecaptcha || grecaptcha.getResponse();
}, "Please fill reCAPTCHA");
这就是全部。
答案 1 :(得分:2)
所以我设法让它奏效了。唯一的问题是用户完成reCaptcha后,消息此字段是必需的不会很快消失。我使用blur,keydown和focusout来检测用户输入并删除错误消息。
JS:
$("#myForm").bind('blur keydown focusout', function(){
var dataArray = $("#myForm").serializeArray(),
dataObj = {};
console.dir(dataArray); //require firebug
//console.log(dataArray);
$(dataArray).each(function(i, field){
dataObj[field.name] = field.value;
});
var recaptcha = (dataObj['g-recaptcha-response']);
if(recaptcha != "") {
$( "#temp" ).remove();
}
});
$( ".register" ).click(function() {
var dataArray = $("#myForm").serializeArray(),
dataObj = {};
console.dir(dataArray); //require firebug
//console.log(dataArray);
$(dataArray).each(function(i, field){
dataObj[field.name] = field.value;
});
var recaptcha = (dataObj['g-recaptcha-response']);
$( "#temp" ).remove();
if(recaptcha == "") {
$("#recaptcha").append('<label id="temp" style="color:red;line-height:normal;font-size: small;">This field is required.</label>');
}
});
});
HTML:
<div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
答案 2 :(得分:1)
您的代码:
<div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="XXXXX"></div>
...与
recaptcha: {
required: true
}
您无法验证<div>
。周期。
jQuery Validate插件只能 验证<input>
,<textarea>
和<select>
元素,这些元素也在{{1容器。
唯一的解决方法是将您的值复制到<form></form>
type="hidden"
元素中,然后将验证应用于该元素。
答案 3 :(得分:-4)
希望您使用HTML5表单标记。
<form>
<div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="XXXXX" required></div>
</form>
最后只需使用必需