Click here to Skip to main content
Click here to Skip to main content

Enhancing the presentation of standard validator outputs

, 13 Jul 2006
Rate this:
Please Sign up or sign in to vote.
How flexible is the normal functionality of ASP.NET validators? In this article, I am going to show how to customize the appearance of the attached control of a validator during an error situation on the server or the client side, or even call a custom client function without postback.

Describing the problem

In a project I am working in, I was faced with a problem. The client asked to change the default presentation of the errors that appeared. He wanted to highlight a background of the field with a custom color when a user entered wrong data on a form. The ordinary technique to show that the validation process failed is to show some red text in a certain position, or just an asterisk. In addition to this, we can also place a ValidationSummary control to show the summarized output. I was searching for some built-in features in .NET to run a custom client function before the postback, but without success.

Sample Image - highlight_validators.jpg

In this article, I am going to show how to add a special Cascading Style Sheet class name to an attached control in an error situation, on the server and the client sides, or even call a custom client function. In addition, I am going to show how to customize validation summary results.

You can download the sources (10.9 Kb), and easily add the functionalities to your form. There is a class library called HighlightValidators. It contains all types of enhanced validators like RequiredValidator, CompareValidator, RangeValidator, RegularExpressionValidator, and CustomValidator. In the demo app (6.52 Kb), you can also find an example form.

How to use the solution

To use it, you need to go through these steps:

  1. Copy UserControls.HighlightValidators.dll from the HighlightValidators/bin/Release folder to the bin folder of your web-application.
  2. Add the following block into the web.config file:
    ...
    <pages>
     <controls>
      <add tagPrefix="uc" assembly="UserControls.HighlightValidators" 
           namespace="UserControls.HighlightValidators" />
     </controls>
    </pages>
    ...

    It will register the Highlight controls from the UserControls.HighlightValidators assembly for the whole web-application.

  3. After that, you can declare the HighlightRequiredValidator, for instance, as follows:
    <uc:HighlightRequiredValidator id=HighlightRequiredValidator1 
     ErrorCssClass="on_error" ErrorMessage="First Name is required" 
     ControlToValidate="TextBox1" runat="Server" />

    I set ErrorCssClass to "on_error". Now, when validation fails, the control TextBox1 will be customized according to the on_error class.

  4. All Highlight validators also have the ErrorClientFunction property. You can use it to call custom client functions in an error situation:
    <uc:HighlightCompareValidator ID="HighlightCompareValidator1" runat="server" 
      ControlToValidate="TextBox1" ErrorMessage="Number of books must be numeric" 
      ErrorCssClass="on_error" ErrorClientFunction="onError" 
      Operator="DataTypeCheck" Type="Integer" />

    Now, you need to declare the function onError() on the page:

    function onError(val)
    {
        alert("Number of books must be numeric");
    }

    Please note that this function takes a parameter, val. This object describes the validator in which the validation has failed. For more information, read the section below.

Diving in to the code

To enhance the standard validators, I used them as inherited classes, and created a new branch of validators with the “Highlight” prefix, because I just wanted to add some desired functionality and maintain compatibility so developers can easily switch between the standard ASP.NET validators and the enhanced Highlight validators.

At first, let’s take a look at how changing the class name works. There are two parts of the code – server and client sides. With the server side, everything is easy: I just added a check whether the validator is valid or if the validation process failed. If it isn’t valid, I add an error class name to the attached control:

protected override void OnPreRender(EventArgs e)
{
    WebControl control = (WebControl)Parent.FindControl(ControlToValidate);
    ClassNameHelper.Remove(control, this.errorCssClass);
    if (!IsValid)
    {
        ClassNameHelper.Add(control, this.errorCssClass);
    }

    base.OnPreRender(e);
}

The ClassNameHelper.Remove() method deletes the error class name in any case, because the previous postback could have failed validation and the class name was added. Now, we need to remove it first, and then check again. If IsValid equals false again, then we need to add the error class name again using the ClassNameHelper.Add() method.

Nothing interesting so far. But let’s figure out how to change the class name of the attached control on the client side before the user postbacks the form. As I said in the introduction section, if we set EnableClientScript to true (its default value), then in case the user enters wrong data, the validation client scripts do not postback the form to the server and add some red text error description or show a validation summary. To investigate this process, I went to the aspnet_client folder and looked into the WebUIValidation.js script file.

I found there, the ValidatorUpdateDisplay function:

function ValidatorUpdateDisplay(val) {
    if (typeof(val.display) == "string") {    
        if (val.display == "None") {
            return;
        }
        if (val.display == "Dynamic") {
            val.style.display = val.isvalid ? "none" : "inline";
            return;
        }
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
}

That’s it! Client scripts use it to show/hide the red error message of the validator. So if we can override it, we can add some additional code, and that will help to implement the enhanced functionalities. To achieve this, I used a little trick – a hijacking. For example, if we have a function test in some included JavaScript file, and we need to override it in the some HTML file, we can do this:

var oldTest;
function newTest()
{
    // call oldTest function
    oldTest();
    
    // execute some additional code
    alert("we've overrided it");
}
window.onload = function()
{
    // hijack test() method
    oldTest = test;
    test = newTest;
}

When the page loads (window.onload event), we save the test() function pointer in the oldTest variable, and replace the current pointer of test() with the newTest() pointer. So now, if we call the test() function, actually we are calling the oldTest() function. Please note that if you use the name of a JavaScript function without parentheses, it’s only a pointer, but if you need to call the function, you need to use “()” at the end.

Let’s go back to the ValidatorUpdateDisplay() function. Now we know how to override it. We also have the val object as a parameter. This object describes the validator which is in the validation process and which changes state after some user action. Some of the important properties of the validator object are described in the following table:

ID Equals the ClientID property of the validator
controltovalidate Contains the ClientID of the control which is attached to the validator
isvalid Indicates whether the validation process failed or not
errormessage Contains the ErrorMessage property

Now, I am going to override the ValidatorUpdateDisplay() function. I need to go through the list of all the Highlight validators placed on the current form and add custom error class names to the controls, in case the validation fails (isvalid == false). I use the Page_HighlightValidators array to save all necessary information about a Highlight validator (validator ClientID, ErrorCssName, and others) to be accessible for client scripts. This happens during the OnLoad event of the Highlight validator:

private string errorCssClass;
public string ErrorCssClass
{
    get { return this.errorCssClass; }
    set { this.errorCssClass = value; }
}

private string errorClientFunction;
public string ErrorClientFunction
{
    get { return this.errorClientFunction; }
    set { this.errorClientFunction = value; }
}

protected override void OnLoad(EventArgs e)
{
    ClientScriptManager cs = Page.ClientScript;
    ...
    Control control = Parent.FindControl(this.ControlToValidate);
    if (control != null)
    {
        if (!cs.IsClientScriptBlockRegistered(this.GetType(), 
             String.Format("HighlightValidation_{0}", this.ClientID)))
        {
            cs.RegisterClientScriptBlock(this.GetType(), 
                String.Format("HighlightValidation_{0}", this.ClientID), 
                String.Format("Page_HighlightValidators.push(
                              new Array('{0}', '{1}', '{2}', '{3}'));", 
                this.ClientID, control.ClientID, this.errorCssClass, 
                this.errorClientFunction), true);
        }
    }
    ...
}

I use the push() method of the Array object to add a new item to the Page_HighlightValidators array because I actually do not know the order of the placed Highlight validators on the form. ErrorCssClass and ErrorClientFunction are new properties of the Highlight validators. We can use them to set custom error class names and client function names that we need to run in case the validation fails.

Eventually, I can use a loop in an already overridden ValidatorUpdateDisplay() function, and add custom error class names if the validation fails:

function newValidatorUpdateDisplay(val)
{
    // call hijacked ValidatorUpdateDisplay() method
    oldValidatorUpdateDisplay(val);
    
    for (i = 0; i < Page_HighlightValidators.length; i++)
    {
        if (val.id == Page_HighlightValidators[i][0] && 
            val.controltovalidate == Page_HighlightValidators[i][1])
        {
            var control = document.getElementById(Page_HighlightValidators[i][1]);
            var errorClassName = Page_HighlightValidators[i][2];
            var errorCallFunction = Page_HighlightValidators[i][3];
            
            // add class and change tooltip
            
            if (errorClassName != "")
            {
                RemoveClassName(control, errorClassName);
                if (!val.isvalid)
                {
                    AddClassName(control, errorClassName);
                    control.title = val.attributes.title.value;
                }
            }
            
            // call custom function            
            if (errorCallFunction != "" && 
                eval("typeof("+errorCallFunction+")") == "function")
            {
                if (!val.isvalid)
                {
                    eval(errorCallFunction+"(val)");
                }
            }
        }
    }
}

Instead of just replacing the class name with the error class name, I use the RemoveClassName and AddClassName functions which have the ability to add and remove class names. They have the ability to attach a few class names, separating them by spaces, like this:

<div class="class_one class_two">...</div>

Please note also that the properties from the class_two class override the properties from class_one. So, we just change the properties which indicate the error, and do not destroy others.

In the code above, I also added calling the custom error client function, and pass the val object to it as the parameter.

Custom validation summary on the client side

Now, we've enhanced the validators, and can indicate to the customer who uses our form the kind of errors that happen, in any way we like, using custom error class names and custom client functions. But let's take a look at the ValidationSummary control. How can its default functionalities be made flexible for us?

For example, I want to place a ValidationSummary control as a div in the center of the browser's window and customize its appearance. For now, let's forget about the asp:ValidationSummary control. And let's go back to the aspnet_client folder again, and open the WebUIValidation.js file. There is a ValidationSummaryOnSubmit() function which the ValidationSummary control calls when it's needed to display the errors list. It's easy to find out that this function uses a global array, Page_Validators, which contains the collective information about all the validators on the current form. OK, that’s what we need. We can use this array to go through all the validators and check their state.

Next, I am going to create a div for my custom Validation Summary control:

<div id="SummaryValidation">
    <span>
        <p style="font-weight:bold">The following errors were occured:</p>
        <ul id="ValidationProblems"></ul>
    </span>
</div>

I already added a header and a list tag, where I am planning to display all the errors. To center the div in the browser window, I am using a little trick. For more details about this, read this perfect article: Horizontally Centered Absolute Positioning.

In the next step, we need to attach the JavaScript function to the Submit event of the form, where we will check all the validators and create a list of errors if they are present; in the other case, we just let the form be posted to the server:

protected void Page_Load(object sender, EventArgs e)
{
    ClientScriptManager cs = Page.ClientScript;
    if (!cs.IsOnSubmitStatementRegistered(this.GetType(), 
         "PrepareValidationSummary"))
    {
        cs.RegisterOnSubmitStatement(this.GetType(), 
           "PrepareValidationSummary", "CheckForm()");
    }
}

Now, I declare the CheckForm() function as follows:

function CheckForm()
{
    if (!Page_IsValid)
    {
        var s = "";
        for (i=0; i<Page_Validators.length; i++) {
            if (!Page_Validators[i].isvalid && 
                 typeof(Page_Validators[i].errormessage) == "string") {
                s += "<li>" + Page_Validators[i].errormessage + "</li>";
            }
        }
        if (s != "")
        {
            document.getElementById('ValidationProblems').innerHTML = s;
            document.getElementById('SummaryValidation').style.display = 'inline';
        }
    }
}

In CheckForm(), I check all the validators for validity and collect error information. Then, if at least one error is present, I display the validation summary.

To hide the validation summary, create the HideValidationSummary() function, and attach it to the document.onlick event so it will disappear after the customer clicks somewhere on the browser’s window.

I hope it is helpful to you, and will appreciate if you leave your opinions, corrections, or any other thoughts. Thanks for your time.

Change history

  • 7/7/2006 - Refactoring: added the EventHelper class to share some recurring blocks of code which are present in each highlight validator declaration.

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

Share

About the Author

Alexander Kleshchevnikov
Web Developer
Ukraine Ukraine
Alexander is freelance web developer with 4 years experience. He has skills in ASP.NET/MS SQL Server, PHP/MySQL, Ruby On Rails, XHTML, CSS. You can contact with me by seigo.ua@gmail.com. Also check my homepage at www.klalex.com.

Comments and Discussions

 
GeneralValidating Checkbox list and Date Operator Type PinmemberGurdeep Toor1-Oct-09 5:45 
GeneralThis utility works great! Pinmembermenachem aaron8-Jul-08 12:33 
QuestionCompare Validator Pinmemberrockinthesixstring29-Apr-08 6:27 
QuestionCant get the SummaryValidation to fire [modified] Pinmemberrockinthesixstring28-Apr-08 20:16 
GeneralRe: Cant get the SummaryValidation to fire Pinmemberrockinthesixstring28-Apr-08 20:18 
Generalbody onload doesn't get fired. Pinmemberseelim999-Aug-07 12:09 
GeneralRe: body onload doesn't get fired. PinmemberTomAgruppa23-Oct-07 6:56 
GeneralThanks xactly what i wanted PinmemberVinay Yeluri17-Apr-07 9:56 
GeneralError message PinmemberIriska1829-Mar-07 3:36 
Its great. But I cant get good result.
I try to paste your methods into big project. I dont know asp&jscript very well.
When I run project, before the page is load, after prerender, get Microsoft JScript runtime error: 'Page_HighlightValidators' is undefined. I dpnt think about it, and difficult to find error.
Help me, if you know answer!!!(maybe)...
General2.0 PinmemberRichardGrimmer28-Mar-07 0:03 
GeneralRe: 2.0 PinmemberStuartHemming19-Feb-08 23:02 
GeneralGreat Job! PinmemberGeorge Mamaladze7-Feb-07 5:39 
GeneralRe: Great Job! PinmemberGeorge Mamaladze7-Feb-07 5:58 
QuestionMore that one validator for a control not working? Pinmemberigoro197520-Sep-06 22:15 
AnswerRe: More that one validator for a control not working? PinmemberAlexander Kleshchevnikov21-Sep-06 7:44 
GeneralRe: More that one validator for a control not working? PinmemberBaTReligion26-Sep-06 7:15 
GeneralRe: More that one validator for a control not working? PinmemberBaTReligion26-Sep-06 7:39 
Generalgood work Pinmembervik2013-Jul-06 22:23 
GeneralRefactoring the code PinmemberG.P.F.6-Jul-06 3:28 
GeneralRe: Refactoring the code PinmemberAlexander Kleshchevnikov11-Jul-06 4:25 
GeneralRe: Refactoring the code PinmemberAlexander Kleshchevnikov13-Jul-06 12:46 
Generalblogged Pinmembervik2024-Jun-06 0:40 
GeneralRe: blogged PinmemberAlexander Kleshchevnikov24-Jun-06 8:44 
GeneralThe validators are always doing the validation server side. Pinmembervik2011-Jun-06 20:49 
GeneralRe: The validators are always doing the validation server side. PinmemberAlexander Kleshchevnikov12-Jun-06 1:52 
GeneralRe: The validators are always doing the validation server side. [modified] Pinmembervik2012-Jun-06 4:14 
GeneralRe: The validators are always doing the validation server side. [modified] PinmemberAlexander Kleshchevnikov12-Jun-06 4:48 
GeneralRe: The validators are always doing the validation server side. Pinmembervik2012-Jun-06 20:07 
GeneralRe: The validators are always doing the validation server side. [modified] PinmemberAlexander Kleshchevnikov13-Jun-06 10:05 
GeneralRe: The validators are always doing the validation server side. Pinmembervik2019-Jun-06 19:59 
GeneralRe: The validators are always doing the validation server side. [modified] PinmemberAlexander Kleshchevnikov21-Jun-06 23:44 
GeneralRe: The validators are always doing the validation server side. Pinmembervik2022-Jun-06 1:09 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 13 Jul 2006
Article Copyright 2006 by Alexander Kleshchevnikov
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid