Matthew Cox Team : Web Development Tags : Web Development

Overriding MVC unobtrusive client validation error placement

Matthew Cox Team : Web Development Tags : Web Development

I love the unobtrusive client validation in .net MVC, it’s simple, easy to use and works. The default behaviour is that when a field fails validation it will add a specific css class to that field (input-validation-error), that way you can highlight to the user the field with the issue. The problem I encountered recently was that I had a field wrapped in 15 pieces of design flare and really needed to add the error class to an element several levels up the DOM hierarchy. I don’t know if this is the best was to solve the issue or even a good way, but it does what I needed it to and it may point others in the right direction. 

    $(function () {

        $('form').each(function (index, item) { 

            var settngs = $.data(item, 'validator').settings;

            var oldErrorFunction = settngs.errorPlacement;

            settngs.errorPlacement = function (error, input

Element) {

                if (error.text() == "") {

                    inputElement.closest(".inp-wrap").removeClass("error");

                }

                else {

                    inputElement.closest(".inp-wrap").addClass("error");

                }

                oldErrorFunction.call(item, error, input

Element);

            };

        });

    });

 

To walk you through everything that’s going in that script, first I grab all the forms on the page, then get the validation settings for the current form. I save out the current errorPlacement function so I don’t have to break the existing functionality and add my new one. The only way I could work out how to determine if the field was valid or not was if the error element had any text in it, then I add or remove my error class accordingly. Finally I just call the oldErrorFunction so that the default error placement code still works. The reason for using the ‘call’ method is to ensure that within the oldErrorFunction ‘this’ is still scoped to the current form, which if you look at ‘jquery.validate.unobtrusive.js’ is how it was originally hooked up.

So as you can see it’s a bit of a hack. I would love to know if anyone knows a better/easier way of getting the same results, but hey, it works on my machine. Special thanks to James and Mark for pointing out inefficiencies in my previous example.

Appendix to blog: Why the tacky badge?

A couple of years back, a developer – Joseph Cooney – wanted a zazzy, ‘certified’ badge to indicate that the programming he had completed… worked.

The badge essentially says ‘buyer beware’, though on a slightly more serious note, tells fellow programmers and management that you’ve certified your work.

The badge is now used by many developers, sort of seriously, sort of as a joke: ‘if it works on my machine, my job here is done.’