Click here to Skip to main content
15,885,278 members
Articles / Web Development / ASP.NET

Change Background Color of Invalid Controls (ASP.NET Validator)

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
31 Mar 2011CPOL1 min read 16.5K   2   1
How to change background color of invalid controls using ASP.NET Validator.

I was working with a customer who has invested a lot in redoing the validation in their web application. I accidentally suggested wouldn’t it be nice if we could change the background or border of the field in question. The customer loved this idea which meant I’d just created more work for myself. After searching about, I wasn’t finding this done for me, so I actually had to write some code instead of cutting and pasting.

If you set a breakpoint on WebForm_OnSubmit and step in, you can check out the .NET validator script. The key thing here is a global array called Page_Validators. From here, it is fairly trivial to test and change something about the control in question.

JavaScript
function fnOnUpdateValidators()
{
    for (var i = 0; i < Page_Validators.length; i++)
    {
        var val = Page_Validators[i];
        var ctrl = document.getElementById(val.controltovalidate);
        if (ctrl != null && ctrl.style != null)
        {
            if (!val.isvalid)
                ctrl.style.background="#FFAAAA";
            else
                ctrl.style.backgroundColor = "";
        }
    }
}

Of course, one problem is if the control already had a background color, it would be lost. This can be circumvented by storing the old value in an attribute or elsewhere. Also, custom validators are a special case so you will need to add the appropriate changes for fields validated in a custom way.

To make sure my function is called, I use the deprecated Page.RegisterOnSubmitStatement(“val”, “fnOnUpdateValidators();”). This will call my function after the validators have fired so the isvalid is up to date.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Avaya Inc.
Ireland Ireland
Formerly a C++ client developer, nowadays I'm all about C# and ASP.NET. Over the years I have mastered some and played with many aspects of .NET.

Follow my blog as I catalogue the more arcane problems I encounter and their solutions at CodingLifestyle.com

Comments and Discussions

 
QuestionI have updated JS for multiple Validators on controls Pin
Samarjeet Singh Tomar8-Jan-13 23:59
Samarjeet Singh Tomar8-Jan-13 23:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.