Click here to Skip to main content
15,887,464 members
Articles / Programming Languages / Javascript
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
13 Dec 2015CPOL 7.6K   3  
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.

JavaScript
/*
 * 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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Network Administrator Busch Systems International
Canada Canada
A Network Administrator by trade, I am a relatively novice coder who is working his way through the world of .NET MVC. I am learning a huge amount through trial-and-error processes, and I am hoping that through writing about some of my experiences, other beginners to .NET can have their path to their goals a little streamlined.

Inspired by some truly talented individuals that I worked with as a Project Manager, coding provides my favorite creative outlet, and I enjoy it for what it is.

Comments and Discussions

 
-- There are no messages in this forum --