jQuery 验证 - 只显示最后验证字段的错误信息

jQuery validation - only show error message of last field validated

如何防止在提交表单时显示多条错误消息?

我只想显示最后验证字段的错误消息:password。我尝试按照不同 post 中的建议使用 errorPlacementjQuery validation - only show one error message$('.alert').remove(); 但没有成功。

到目前为止我得到了什么:

<script>
    let form = $('#login');

    $('#login').validate({
        onkeyup: false,
        onclick: false,
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        errorPlacement: function(error) {
            $('.alert').remove();

            let div = $(
                '<div class="alert alert-warning alert-dismissable">\n' +
                '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>\n' +
                '<h4><i class="icon fa fa-warning"></i>Opgepast!</h4>\n' +
                '<p>' + error.text() + '</p>\n' +
                '</div>'
            );

            div.insertBefore(form);
        },
        messages: {
            username: {
                required: "Gelieve een gebruikersnaam in te vullen."
            },
            password: {
                required: "Gelieve een wachtwoord in te vullen."
            }
        }
    });
</script>

按照@Sparky 的建议将errorPlacement 更改为showErrors。结果:

showErrors: function(object) {
    $('.alert').remove();

    let amount = Object.keys(object).length;

    if(amount > 0){
        let key = Object.keys(object)[0];
        let value = object[key];

        let div = $(
          '<div class="alert alert-warning alert-dismissable">\n' +
          '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>\n' + 
          '<h4><i class="icon fa fa-warning"></i>Opgepast!</h4>\n' +
          '<p>' + value + '</p></div>');

        div.insertBefore(form);
    }