"实时"更新验证摘要

nix*_*xon 11 asp.net-mvc jquery jquery-validate asp.net-mvc-4

嗨,我正在使用MVC4与客户端验证.这非常适合显示字段旁边的验证消息.

我添加了验证摘要:

 @Html.ValidationSummary(false)
Run Code Online (Sandbox Code Playgroud)

这是有效的,客户端'全部.我希望它表现得与众不同; 目前,验证摘要中的消息仅在单击提交按钮时更改.我希望它们以与每个字段的验证消息类似的方式动态填充.

有人可以建议一种方法来实现这一目标吗

有关触发摘要更新的内容的任何信息都会很棒.

Tor*_*ell 7

我已经设置了验证摘要以"实时"更新,同时考虑以下因素:

  1. 在摘要可见时更新摘要(在页面验证/提交后)
  2. 当一切有效时清除摘要

让我们提取验证器,重写showErrors()并实现我们的逻辑:

var validator = $('form').data('validator');
validator.settings.showErrors = function (map, errors) {
    this.defaultShowErrors();
    if ($('div[data-valmsg-summary=true] li:visible').length) {
        this.checkForm();
        if (this.errorList.length)
            $(this.currentForm).triggerHandler("invalid-form", [this]);
        else
            $(this.currentForm).resetSummary();
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我在整个网站上使用此解决方案,因此我创建了以下init(onready):

$('form').each(function () {
    var validator = $(this).data('validator');
    if (validator) {
        validator.settings.showErrors = function (map, errors) {
            this.defaultShowErrors();
            if ($('div[data-valmsg-summary=true] li:visible').length) {
                this.checkForm();
                if (this.errorList.length)
                    $(this.currentForm).triggerHandler("invalid-form", [this]);
                else
                    $(this.currentForm).resetSummary();
            }
        };
    }
});
Run Code Online (Sandbox Code Playgroud)

这是上面使用的resetSummary:

jQuery.fn.resetSummary = function () {
    var form = this.is('form') ? this : this.closest('form');
    form.find("[data-valmsg-summary=true]")
        .removeClass("validation-summary-errors")
        .addClass("validation-summary-valid")
        .find("ul")
        .empty();
    return this;
};
Run Code Online (Sandbox Code Playgroud)