Back to all posts

ASP.NET MVC 5 & Bootstrap 3 Validation Usage

Posted on Aug 25, 2015

Posted in category:
Development
ASP.NET

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.

jQuery Validation Integration Script
(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!