我设置了一次验证所有形式的表单,但是我添加了Google重新验证码,并希望在出现所有其他错误时出现以下#grecaptchaError。
现在,如果所有内容均为空白,然后单击“提交”,则将显示唯一的Recaptcha错误...一旦选中该框以进行验证,然后其他错误就会出现。该站点密钥对我的域是正确的,并且可以正常工作,因此请忽略Codepen中的错误。重新排列jQuery的任何帮助将不胜感激。
function checkCaptcha() {
console.log('checkCaptcha');
if(allowSubmit) return true;
// e.preventDefault();
$('#grecaptchaError').text('Please confirm that you are not a robot');
return false;
}
更新:
我发现了一个回调方法,该方法检查一个隐藏值,现在所有显示错误都同时显示,我只知道jquery不合适,因为它直接循环通过而没有点击submit按钮并给出成功消息。当我在底部添加$.ajax({
时,它开始这样做。
新的Codepen链接为here
答案 0 :(得分:0)
您检查错误的顺序类似于验证码-> jQuery验证。这就是为什么您没有看到其他错误消息的原因,因为如果出现验证码错误消息,您将返回。
我已经更新了您的Javascript代码,因此首先运行jQuery验证,如果验证成功,则运行验证码。
var allowSubmit = false;
function captchaCb(response) {
allowSubmit = true;
console.log('this is reCaptcha response: ' + response);
}
function checkCaptcha() {
console.log('checkCaptcha');
if(allowSubmit) return true;
// e.preventDefault();
$('#grecaptchaError').text('Please confirm that you are not a robot');
return false;
}
$("#form-submit").click(function() {
$("#contact-form").submit();
});
$("#contact-form").validate({
rules: {
name: {
required: true,
minlength: 2,
},
email: {
required: true,
email: true,
},
budget: {
required: true,
},
message: {
required: true,
minlength: 5,
},
},
messages: {
name: {
required: "come on, you have a name don't you?",
minlength: "your name must consist of at least 2 characters"
},
email: {
required: "no email, no message"
},
budget: {
required: "Please select your budget"
},
message: {
required: "um...yea, you have to write something to send this form.",
minlength: "thats all? really?"
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "name" ) {
error.appendTo('#nameError');
}
if (element.attr("name") == "email" ) {
error.appendTo('#emailError');
}
if (element.attr("name") == "budget" ) {
error.appendTo('#budgetError');
}
if (element.attr("name") == "g-recaptcha-response" ) {
error.appendTo('#grecaptchaError');
}
if (element.attr("name") == "message" ) {
error.appendTo('#messageError');
}
},
submitHandler: function(form) {
if (!checkCaptcha()) {
console.log('captcha error occurs ');
return;
}
$.ajax({
//dataType: "jsonp",
url: "example.com",
data: $("#contact-form").serialize()
}).done(function() {
//callback which can be used to show a thank you message
//and reset the form
$("#contact-form").hide();
$(".form-thank-you").fadeIn("400");
});
return false; //to stop the form from submitting
}
});