[英]Form validation only showing first error message
我正在验证表单,并且只能显示第一条错误消息:
ContactUs.prototype.desktopErrors = function(){
var THIS = this;
THIS.$el.find('#submit').on('click', function(){
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
} else if (!$('#lastName').val().length) {
$('.nameErrs li').text("We can't verify your last name")
} else if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
} else if (!$('#lastName').val().length) {
$('.emailErrs li').text("We can't verify the subject")
}
});
return THIS;
};
这是JADE:
.row
.form-group
label.first_name_label(for="firstName") First Name*
input.first_name_input(required type="text" class="form-control" id="firstName")
.form-group
label.last_name_label(for="lastName") Last Name*
input.last_name_input(required type="text" class="form-control" id="lastName")
ul.nameErrs
li.full
.row
.form-group
label.email_address_label(for="emailAddress") Email Address*
input.email_address_input(required type="email" class="form-control" id="emailAddress")
.form-group
label.(for="subject") Subject*
input.(required type="text" class="form-control" id="subject")
ul.emailErrs
li.full
因此,如果所有字段均为空,则无法显示所有错误消息,仅显示第一个错误消息。
有什么建议吗?
if else
是失败快速逻辑构造
您需要在所有字段中使用if blocks
THIS.$el.find('#submit').on('click', function(){
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
}
if (!$('#lastName').val().length) {
$('.nameErrs li').text("We can't verify your last name")
}
if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
}
if (!$('#lastName').val().length) {
$('.emailErrs li').text("We can't verify the subject")
}
});
断开else if
逻辑。 然后附加文本,以免覆盖。
THIS.$el.find('#submit').on('click', function(){
$('.nameErrs li').text("");
$('.emailErrs li').text("");
if (!$('#firstName').val().length) {
$('.nameErrs li').text("We can't verify your name")
}
if (!$('#lastName').val().length) {
$('.nameErrs li').text( $('.nameErrs li').text() + "We can't verify your last name")
}
if (!$('#emailAddress').val().length) {
$('.emailErrs li').text("We can't verify your email address")
}
// FYI: in your snippet this is a reevaluation of lastname
if (!$('#subject').val().length) {
$('.emailErrs li').text( $('.emailErrs li').text() + "We can't verify the subject")
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.