简体   繁体   English

Jquery 验证 - 在急切验证期间显示验证摘要?

[英]Jquery validation - show validation summary during eager validation?

Is it possible to get jquery validation to show the validation summary using eager validation?是否可以使用急切验证来获得 jquery 验证以显示验证摘要?

I'm using MVC 3 (if it matters) and my forms validate when each element loses focus:我正在使用 MVC 3(如果重要的话)并且我的表单在每个元素失去焦点时进行验证:

$('#myform').validate({ onfocusout: function(element) { $(element).valid(); } };

This shows individual errors on each field, however I also want to show those errors in the validation summary block.这显示了每个字段上的单个错误,但是我还想在验证摘要块中显示这些错误。 However, that validation summary only shows up when the form is submitted, not on lost focus.但是,该验证摘要仅在提交表单时显示,而不是在失去焦点时显示。

I've tried hooking into showErrors, however that only gives me the current field error, not the current list of errors.我试过挂钩 showErrors,但是这只给了我当前的字段错误,而不是当前的错误列表。


For completeness, here's the form code:为了完整起见,这里是表单代码:

@using (Ajax.BeginForm(...))
{

  <div class="field-panel">
    @Html.EditorFor(m => m.PatientID)
    ...

  </div>
  <input type="submit" class="carecon-button-next" value="Next" />
  @Html.ValidationSummary(null, new { @class = "validation-summary" })
}

Ok, I think I figured this out.好吧,我想我想通了。

The issue is actually due to using the unobtrusive validation with MVC 3, since it does the jQuery validation initialization for you.这个问题实际上是由于在 MVC 3 中使用了不显眼的验证,因为它会为您执行 jQuery 验证初始化。 Thus the only way to configure validation is by using form.data("validator").settings .因此,配置验证的唯一方法是使用form.data("validator").settings However, trying to set the errorLabelContainer via this method, ie:但是,尝试通过此方法设置errorLabelContainer ,即:

$("#form").data("validator").settings.errorLabelContainer = "#messageBox";

... doesn't work, because jQuery's validation only uses this value internally in it's init() function, to configure a bunch of other settings like containers , etc. I tried emulating what it does, or even calling $("#form").data("validator").init() again after setting the errorLabelContainer , but doing so caused weird behavior and hosed a bunch of other settings. ...不起作用,因为 jQuery 的验证仅在它的 init() 函数内部使用此值,以配置一堆其他设置,如容器等。我尝试模拟它的作用,甚至调用$("#form").data("validator").init()再次设置errorLabelContainer ,但这样做会导致奇怪的行为并冲洗了一堆其他设置。

So I took a different approach.所以我采取了不同的方法。 First, I provided a place for MVC to put in the individual error strings using @Html.ValidationMessageFor() , and adding display:none to keep it hidden:首先,我为 MVC 提供了一个使用@Html.ValidationMessageFor()放入单个错误字符串的位置,并添加display:none以使其隐藏:

@using (Ajax.BeginForm(...))
{

  <div class="field-panel">
    @Html.EditorFor(m => m.PatientID)
    @Html.ValidationMessageFor(m => m.PatientID, null, new { style = "display:none"})
    ...

  </div>
  <input type="submit" class="carecon-button-next" value="Next" />
  <ul id="error-summary">
  </ul>
}

Then, in the showErrors callback, I copy those strings in to the validation summary after calling defaultShowErrors() :然后,在showErrors回调中,我调用defaultShowErrors()后将这些字符串复制到验证摘要中:

    $("#form").data("validator").settings.onfocusout = function (element) { $(element).valid(); };
    $("#form").data("validator").settings.showErrors = function (errorMap, errorList) {
        this.defaultShowErrors();
        $("#error-summary").empty();
        $(".field-validation-error span", $("#form"))
            .clone()
            .appendTo("#error-summary")
            .wrap("<li>");

    };

This gave me the behavior I wanted, showing/hiding the validation errors as a list in the summary as the user filled out the fields on the form.这给了我想要的行为,当用户填写表单上的字段时,将验证错误显示/隐藏为摘要中的列表。

I was having similar troubles and wrote this, it seems like an easy way to get the behavior you are looking for:我遇到了类似的麻烦并写了这个,这似乎是一种获得您正在寻找的行为的简单方法:

function EnableEagerValidation(){
    var itemsNeedingValidation = $('*[data-val="true"]');
    itemsNeedingValidation.each(function () {
        $(this).blur(function(){$(this).closest("form").valid();});
    });
}

This is from the demo page ;这是来自演示页面 the invalidHandler and the code to create an error summary. invalidHandler和用于创建错误摘要的代码。 But it's triggered on form submit which is not what you requested.但它是在form提交时触发的,这不是您要求的。

invalidHandler: function(e, validator) {
    var errors = validator.numberOfInvalids();
        if (errors) {
            var message = errors == 1
                 ? 'You missed 1 field. It has been highlighted below'
                 : 'You missed ' + errors + ' fields.  They have been highlighted below';
                 $("div.error span").html(message);
                 $("div.error").show();
        } else {
            $("div.error").hide();
        }
},

However, the errorLabelContainer: method does not require form submission.但是, errorLabelContainer:方法不需要form提交。 As per the documentation , "All error labels are displayed inside an unordered list with the ID "messageBox", as specified by the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages."根据文档“所有错误标签都显示在 ID 为“messageBox”的无序列表中,由作为 errorContainer 选项传递的选择器指定。所有错误元素都包含在 li 元素中,以创建消息列表。”

errorLabelContainer: "#messageBox",

Here is a crude demo showing validation using onfocusout .这是一个粗略的演示,显示了使用onfocusout验证。 There is no submit button to prove this point.没有提交按钮可以证明这一点。 The #messageBox accumulates all the messages as they are collected. #messageBox会在收集到所有消息时累积所有消息。

http://jsfiddle.net/sparky672/bAN2Q/ http://jsfiddle.net/sparky672/bAN2Q/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM