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:
Inspect the initial design
Just hit F5
and go to the log in view and click Log in
. You will see something like this:
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
:
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:
That was all for now. Hope you find it useful.
Cheers,
//Daniel