javascript - 表单验证仅显示第一条错误消息

标签 javascript jquery

我正在验证表单,但只能显示第一条错误消息:

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;
};

这是杰德:

    .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 block

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")
    }
});

关于javascript - 表单验证仅显示第一条错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028519/

相关文章:

javascript - 如何选择一个按钮并在单击该按钮时删除该按钮的祖 parent div?

javascript - 不使用 Flexbox 的响应式 div

javascript - 表单重置函数返回未定义

javascript - 我的对象不是通过引用更新的,逻辑有什么问题?

javascript - 滚动页面时如何准确定位 div 相对于鼠标指针的位置?

javascript - 如何使用 jquery 将 URL 字符串分成几部分并插入到变量中

jQuery 无法在 AJAX 函数内定义变量

jQuery - 在 HTML 下拉菜单中获取特定范围的项目

javascript - 使用 contenteditable div 修复光标位置正确

javascript - Bing Ajax v7 未使用 IE9 触发点击事件