仅显示一个错误消息 [英] Show only first error message

查看:137
本文介绍了仅显示一个错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC3对于同时具有服务器和客户端验证的一种形式。我展示的错误消息为输入上述气球。由于错误的presentation,我需要只在一个时间显示一个差错,否则气球倾向于掩盖其他领域也可能是错误的。

I am using ASP.NET MVC3 for a form that has both server and client validations. I'm showing error messages as balloons above the inputs. Due to the presentation of the errors, I need to only show one error at a time, otherwise the balloons tend to obscure other fields that may also be in error.

我如何自定义验证行为只会使第一个错误信息?

How can I customize the validation behavior to only render the first error message?

编辑:请注意,形式同时具有服务器和客户端验证,而我只想显示整个形式(而不是每场)

Please notice that the form has both server and client validations, and that I only want to show the first error message for the entire form (not per field).

推荐答案

在万一有人需要它,我想出了一个解决方案是实现页面的底部添加以下脚本。这挂接到现有的JavaScript验证,以动态地隐藏所有,但在表单的第一个错误。

In case anyone needs it, the solution I came up with is to add the following script towards the bottom of the page. This hooks into the existing javascript validation to dynamically hide all but the first error in the form.

<script>
    $(function() {
        var form = $('form')[0];
        var settings = $.data(form, 'validator').settings;
        var errorPlacementFunction = settings.errorPlacement;
        var successFunction = settings.success;

        settings.errorPlacement = function(error, inputElement) {
            errorPlacementFunction(error, inputElement);
            showOneError();
        }
        settings.success = function (error) {
            successFunction(error);
            showOneError();
        }
        function showOneError() {
            var $errors = $(form).find(".field-validation-error");
            $errors.slice(1).hide();
            $errors.filter(":first:not(:visible)").show();
        }
    });
</script>

这篇关于仅显示一个错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆