Blogs

ASP.NET MVC 5 & Bootstrap 3 Validation Usage

25 Aug

There have been many posts out there that show various solutions to use ASP.NET MVC 5 with Bootstrap 3 style input validation.  Some of the solutions are far better than others, and others looked perfectly elegant, yet they didn't necessarily result in changes working the way that one would expect.   After trying multiple solutions I found that I was able to take one of the more elegant solutions and it was working for "success" but wasn't working for error states, so I decided to dive in an fix it for my situation.

Upon researching this in more detail I found that many people were experiencing the same issues that I was.  We had the most current versions of Bootstrap, jQuery, and jQuery Validation yet the errors rather than adding "has-error" as a CSS class were adding "input-validation-error", which is singularly unhelpful to our Bootstrap supplied styles.  In my situation I was able to add the following jQuery to my jqueryVal bundle, just after the inclusion of the jQuery libraries.

(function ($) {
    var defaultOptions = {
        validClass: 'has-success',
        errorClass: 'has-error',
        highlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group")
                .removeClass(validClass)
                .addClass('has-error');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).closest(".form-group")
            .removeClass('has-error')
            .addClass(validClass);
        }
    };

    $.validator.setDefaults(defaultOptions);

    $.validator.unobtrusive.options = {
        errorClass: defaultOptions.errorClass,
        validClass: defaultOptions.validClass,
    };
})(jQuery);

The important piece here was the "addClass" and "removeClass" items. The difference in my needed code was the hard-coded 'has-error' class to those calls, rather than using the default option values. I'm not 100% sure of why, but this is stable for me now and I thought it was worth sharing!

tags: Quick Tips, ASP.NET MVC, .NET 4.5, .NET 4.6
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Connect with Mitchel

I hope the information here has been helpful. To stay connected you can also subscribe to blog updates via email, contact Mitchel about consulting services, or reach out for assistance via CodeMendor

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.