Introduction
Upon Jquery Validate marking a form field as invalid within your .NET MVC form, .NET likes to apply its own '.has-validation-error
" class to the input element, which doesn't really fly with the nice Bootsrap validation classes such as ".has-error
" and ".has-success
".
In checking on Stack Overflow, a lot of answers suggested messing with the settings that drive JQuery Validation, which I really couldn't be bothered wasting time in figuring out how to do, so I wrote the below chunk of JavaScript which handles it for me. It's not exactly pretty or exhaustive, but it gets the job done. For quick and simple applications, the costs of doing something like messing with JQuery Validate settings sometime outweigh the benefits...
Using the Code
The below code fires upon any form-control (a parent element to any input) losing focus. It will call JQuery Validate
's .valid()
method to check whether the input is valid and will apply the relevant class.
It could do with some tweaking so if you have any comments, please do post them, below.
$(".form-control").focusout(function () {
if (!$(this).valid()) {
$(this).closest(".form-group").addClass("has-error");
}
else if ($(this).valid()) {
$(this).closest(".form-group").addClass("has-success");
}
else if (!$(this).val()) {
$(this).removeClass("has-error has-success");
}
});
History
- 14th December, 2015: First copy of tip