使用 jQuery 进行表单验证。我的所有验证似乎都正常工作。
如果您提交没有数据的表单,则会出现所有正确的错误。
如果您修复其中一个字段,则该字段的错误消息不会清除。
我认为这可能是我的逻辑有问题,但不确定是否有一种简单的方法可以再次尝试检查验证?
我在 jQuery 中提交的代码在这里。前四个验证函数用于检查错误并显示错误(如果有)。如果有任何错误,表单将无法提交。如果没有错误,将显示警报并允许提交。我知道问题在于,在第一个 if 语句发现错误之后 - 无法查看错误是否已修复并清除该错误。所以我不知道该去哪里 - 循环可能会更好吗?
// On Form Submission Validate Form
$("#contact_submit button").click(function(event){
error_name = validateName();
error_email = validateEmail();
error_activity = validateActivities();
isCreditIssue = validateCredit();
event.preventDefault();
var valid = true;
if ((error_name) || (error_email) || (error_activity) || (isCreditIssue)){
console.log("errors");
valid = false;
} else {
alert('GREAT! form completed');
valid = true;
}
if (valid) {
return;
}
最佳答案
当表单值在许多地方变得有效时,您遗漏了 hide
语句。举个例子(在 validateZip
中):
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
errorZip = false;
}
您应该将其替换为:
if ((!errorZip)||(zip!= 5)){
$(".error_zip").show();
errorZip = true;
console.log('zip issue');
} else {
$(".error_zip").hide();
errorZip = false;
}
关于javascript - jQuery 表单验证——正确提交而不是清除错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244081/