Over Macho Grande

Sunday, April 15, 2012

MVC3 Unobtrusive Validation, Bootstrap, and You

I _really_ like Twitter's Bootstrap.  It saves me from making any number of questionable content design choices.  I'm using it in an MVC3 project and one of the things that bugged me was the inability to get Microsoft's unobtrusive validation working with the fancy form control states in Bootstrap.

Well, after looking around on StackOverflow and poking and prodding MVC, here's what I've got:
If you correct the error, the state changes away from error and you get this:
I hacked this into place by inserting a shim error placement function.  It saves a handle to the original Microsoft implementation, changes the class on the nearest div with a CSS class of "control-group" and then calls the Microsoft implementation to display the actual error text.

$(document).ready(function () {
            var esettings = $.data($('form')[0], 'validator').settings;
            // Get a handle to the original errorPlacement function
            var originalFunction = esettings.errorPlacement;
            esettings.errorPlacement = function (error, inputElement) {
                // Although you have access to the form via $(this),
                // getElementById should be efficient
                // NOTE:  This assumes that the name and id properties are the same
                var id = "#" + inputElement[0].name;
                var controlGroup = $(id).closest("div.control-group");
                // error[0].innerHTML contains the validation error message
                if (0 == error[0].innerHTML.length) {
                } else {
                // Call the original function
                originalFunction(error, inputElement);
 There's probably a much smarter way to do this, but this works well enough for now.

Labels: , ,