Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Quick & Dirty Solution to Employing .NET's .input-validation-error Class w/ Bootstrap's .has-error & .has-success Classes

0.00/5 (No votes)
13 Dec 2015 1  
A quick and dirty way to ensure your .NET MVC forms apply Bootstrap's .has-error and .has-success classes, instead of relying on .NET's .input-validation-error class.

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.

/*
 * Title: Form Validation
 * Description: Adjusts for .NET .input-validation-error class so
 * that the Bootstrap variants "has-error" or "has-success" are used.
 */
$(".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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here