danielwertheim

danielwertheim


notes from a passionate developer

Share


Sections


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

ASP.Net MVC 5 - quick tip for unobtrusive validation and Bootstrap styling

Remarkable. If you just create a new ASP.Net MVC 5 project, it comes with Bootstrap enabled. If you have selected to include scaffolded code for Individual user accounts, you also get e.g. a log in form generated for you. Now, just click the Log in button and look at the visual design of the validation errors. It does not use Bootstraps e.g. has-error on the form-group, hence you loose some “intended” Bootstrap validation behavior. There are various tips for this. Mine consists of a tiny piece of JavaScript and then you are done with it. Lets have a look.

Create the project

I just started Visual Studio 2013 and created a new ASP.Net Web Application and went through the dialogs to get a MVC project created for me, according to the following screenshots:

bs-mvc-jq-val-file-new-project-a

bs-mvc-jq-val-file-new-project-b

Inspect the initial design

Just hit F5 and go to the log in view and click Log in. You will see something like this:

bs-mvc-jq-val-login-validation-ugly

As you can see it does miss some markup as suggested in the Bootstrap docs. Lets fix it.

The solution

Just add a JavaScript file, e.g. _extensions.js in the Scripts folder and then include it in the BundleConfig:

bs-mvc-jq-val-add-bundle

The file it self should hook into the jQuery.validator via its extension points.

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

    $.validator.setDefaults(defaultOptions);

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

Now, compile and look at the same log in view again and kick of the validation:

bs-mvc-jq-val-login-validation-bootstrapified

That was all for now. Hope you find it useful.

Cheers,

//Daniel

View Comments