Set the CSS class of ASP.NET invalid controls using jQuery

The ASP.NET validation controls are a very quick and effective way to add client-side & server-side validation to your web forms but they lack one very important feature out of the box: the ability to change the CSS class of the controls that are invalid. Changing the class of the invalid controls will allow you to style them in such a way that they help bring attention to the fact that the user needs to do something more to complete the form successfully.

It is quite simple to add this functionality (for clients with JavaScript enabled at least) using a little bit of JavaScript and everybody’s favourite JavaScript library, jQuery!

First of all, set the CssClass property of all your validator controls to “validation-error”. The easiest way to achieve this is by using a skin file. See this post for more details on how to do this.

Then add the following to your site’s JavaScript file (assuming you’re already using jQuery):

 
/// <reference path="jquery-1.3.1.js" />

$(document).ready(function(e) {
    $("span.validation-error")
        .bind("DOMAttrModified propertychange", function(e) {
            // Exit early if IE because it throws this event lots more
            if (e.originalEvent.propertyName && e.originalEvent.propertyName != "isvalid") return;

            var controlToValidate = $("#" + this.controltovalidate);
            var validators = controlToValidate.attr("Validators");
            if (validators == null) return;

            var isValid = true;
            $(validators).each(function() {
                if (this.isvalid !== true) {
                    isValid = false;
                }
            });

            if (isValid) {
                controlToValidate.removeClass("error");
            } else {
                controlToValidate.addClass("error");
            }
        });
});

And there you have it. Now when any validator on your form has the isValid property tripped to false on the client side, the CSS class of the offending control will be changed to “error”.


9 Comments on “Set the CSS class of ASP.NET invalid controls using jQuery”

  1. […] controls to change invalid control’s CSS class on non-JavaScript clients In my previous post I showed how you could add support for the ASP.NET validation controls to automatically change the […]

  2. Aaron Powell says:

    wouldn’t it be safer to bind to the click event of the controls which cause validation of that validation group? I thought ‘propertychange’ isn’t a supported properly across all browsers?

  3. The propertychange event is only supported by IE, however the DOMAttrModified event, which I’m also subscribing to, is supported in Firefox and Opera. Unfortunately neither event is supported in Safari/Webkit (see https://bugs.webkit.org/show_bug.cgi?id=8191).

    Binding to the click event has its problems too. What if I have a drop down list? Binding to its click event will do little if I use the keyboard to select an invalid value. Furthermore I want the class to change when the validator appears, not just when the form is submitted (e.g. when I move focus of a textbox with an invalid value, ASP.NET will show the validation message).

    Of course I could bind to a bunch more events until I believe I have them all, but I’d rather observe the property that is set as a result of all that work anyway, rather than try to replicate it myself. Plus this example is quite generic and portable.

  4. adam says:

    Lovely job Damian. Just what I was looking for!

  5. haris says:

    Brilliant work Damian.

    There is one issue though.
    If you set the validator’s Display property to “none”. It stops working with firefox, however it still works perfectly fine with IE.

    What I wanna do is to show the error message within the ValidationSummary and highlight the field which is invalid.

    Any ideas how to do that? Appreciate any help.

    • TheMG says:

      I set the display to none in the CSS class instead of using the validators display property and it seemed to work fine for me.

  6. Harry Wong says:

    After spending two days on this feature, yours is the best and easiest solution to customize validation control and control it validates. Excellent job, my friend.

  7. Rob Grabowski says:

    This worked great until I added textmode=password to my asp:textbox password fields. Any idea how to work around this?

  8. […] important feature out of the box: the ability to change the CSS class of the controls that are… [full post] Damian Edwards Coming up blank uncategorizedasp.netcssjquery 0 0 […]