65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Dec 13, 2015

CPOL
viewsIcon

7751

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