Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only first error message

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?

Edit: 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).

like image 362
gxclarke Avatar asked Jul 07 '26 18:07

gxclarke


1 Answers

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>
like image 75
gxclarke Avatar answered Jul 14 '26 07:07

gxclarke