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

Smart Validation Summary

Rate me:
Please Sign up or sign in to vote.
4.15/5 (8 votes)
17 Jan 20053 min read 86.8K   43   12
An article demonstrating creation of a custom ASP.NET validation summary control with highlighting of invalid form fields intelligently.

Sample Image - smartvalidationsummary.jpg

Overview

I believe that everyone has experienced filling in a form. If there are errord, it is annoying to find them. You know the error but you cannot find it right away. Highlighting an error field is the most preferred method for the end user. I did remember I created a similar solution in ASP before, but it required a lot of code to handle this eye-catching solution.

Introduction

The built-in ASP.NET Validation Summary Control is good. It is easy for us to show a summary of errors in a form. However, it is difficult to search the invalid entries if we have got too many fields in a form. The best solution is to highlight the field if it is invalid. Recently, I developed this solution and would like to share it with you.

The code

First of all, we need to create a control class to override the Validation Summary control.

C#
public class SmartValidationSummary : 
        System.Web.UI.WebControls.ValidationSummary

The ErrorCssClass variable is created for defining the CSS class of a field when it is in error. We use the viewstate variable ViewState["ErrorCssClass"] to store the CSS class.

C#
[
Bindable(true),
Category("Appearance"),
DefaultValue(""),
Description("CSS class name applied to the invalid control.")
]
public string ErrorCssClass
{
    get
    {
        object o = ViewState["ErrorCssClass"];
        if (o != null)
            return (string) o;
        else
            return String.Empty;
    }

    set
    {
        ViewState["ErrorCssClass"] = value;
    }
}

On the pre-rendering process, we need to search through the form for the RequriedFieldValidator and check for error.

C#
protected override void OnPreRender(EventArgs e)
{
    foreach(Control ctlForm in Page.Controls)
    {
        if (ctlForm.GetType() == typeof(HtmlForm))
        {
            ControlCollection ccForm = ctlForm.Controls;
            foreach(Control ctlItem in ccForm)
            {
                if (ctlItem.GetType() == typeof(RequiredFieldValidator))
                    ProcessRequiredFieldValidator(ctlItem);
            }
        }
    } 

    base.OnPreRender (e);
}

If the ControlToValidate is defined and it is a TextBox, that means it is the target field that we need to control its appearance.

C#
private void ProcessRequiredFieldValidator(Control ctlItem)
{
    RequiredFieldValidator vdrItem = (RequiredFieldValidator)ctlItem;

    if (vdrItem.ControlToValidate != string.Empty)
    {
        string strInvalid = vdrItem.ControlToValidate;
        Control ctlToValidateItem = Page.FindControl(strInvalid);
        if(ctlToValidateItem.GetType() == typeof(TextBox))
            ProcessTextBox(ctlToValidateItem, vdrItem.IsValid);
    }
}

If there is an error in the TextBox, we set the CSS class to the ErrorCssClass and save the original CSS class to the viewstate variable. Otherwise, we need to restore it to the original state from the saved viewstate variable.

C#
private void ProcessTextBox(Control ctlToValidateItem, bool boolIsValid)
{
    TextBox txtItem = (TextBox)ctlToValidateItem;

    if (boolIsValid)
    {
        if (ViewState[txtItem.ClientID + "CssClass"] != null)
        {
            txtItem.CssClass = ViewState[txtItem.ClientID + "CssClass"].ToString();
            ViewState[txtItem.ClientID + "CssClass"] = null;
        }
    }
    else
    {
        if (txtItem.CssClass != this.ErrorCssClass)
            ViewState[txtItem.ClientID + "CssClass"] = txtItem.CssClass;
        txtItem.CssClass = this.ErrorCssClass;
    }
}

Installing the control

All you have to do is unzip the source file and copy the smart.dll file to your project \bin\ folder.

Using the control

  1. Add the smart.dll to your project references and register the smart.dll to the aspx page with the following code:
    ASP.NET
    <%@ Register TagPrefix="Smart" 
           Namespace="Smart.Web.UI.WebControls" Assembly="Smart" %>
  2. Use the following code instead of the basic 'Validation Summary control' from ASP.NET. You need to specify the CSS class when there is an error in a required validator.
    ASP.NET
    <smart:smartvalidationsummary id="SmartValidationSummary1" runat="server" 
     CssClass="inputSummary" ErrorCssClass="inputError" 
     HeaderText="We're sorry.  We need the following information ...">
    </smart:smartvalidationsummary>
  3. Define your RequiredFieldValidator as usual but you have to disable the attribute EnableClientScript.
    ASP.NET
    <asp:requiredfieldvalidator id="rfvFirstName" runat="server" 
     ErrorMessage="First Name" ControlToValidate="txtFirstName" 
     EnableClientScript="False">*</asp:requiredfieldvalidator>

Note: If you still have difficulties to implement this solution, please refer to my demo project.

Limitation

As this is a server-side only control, all validators using the smart Validation Summary must not be set to use the client script.

Further Enhancements

There are lots of enhancements required for this project. Following is my expectation:

  1. Adding JavaScript code to handle the client-side validation will be in the next version of my project.
  2. Using other validators are almost the same as the RequiredFieldValidator. Although I only use RequiredFieldValidator in this project, you can easily enhance it with other validators such as CompareValidator, RegularExpressionValidator or even custom validators.
  3. For my requirement, I only need to use the TextBox control. Using the same concept, this validation summary control can also apply to other controls such as DropDownList, RadioButton etc.

History

  • Jan 18, 2004: Released version 1.0.

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


Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalbug in master Pin
mona_mvhd21-Nov-08 21:41
mona_mvhd21-Nov-08 21:41 
GeneralRe: bug in master Pin
mona_mvhd22-Nov-08 0:33
mona_mvhd22-Nov-08 0:33 
GeneralRe: bug in master Pin
mona_mvhd22-Dec-08 21:48
mona_mvhd22-Dec-08 21:48 
Thanx but Still can't use in master page.I don't now why.when I use this control in ordinary page without mastre page it's work well.but when I insert it in a page that has a master page it dosen't work.whould you help me and tell me the reason?
GeneralBad Idea Pin
dpak117020-Jun-08 9:12
dpak117020-Jun-08 9:12 
GeneralSmart Validation Summary and Master Page Pin
RovedaC26-Jul-06 3:11
RovedaC26-Jul-06 3:11 
GeneralGreat Pin
SPYKING27-Feb-06 22:10
SPYKING27-Feb-06 22:10 
GeneralNice idea... Pin
DanielHac8-Feb-05 15:06
DanielHac8-Feb-05 15:06 
GeneralRe: Nice idea... Pin
Mr. Tommy Li10-Feb-05 14:09
Mr. Tommy Li10-Feb-05 14:09 
GeneralRe: Nice idea... Pin
DanielHac10-Feb-05 14:22
DanielHac10-Feb-05 14:22 
GeneralVB.NET Version &amp; Improvements Pin
scott.simmons27-Jan-05 5:15
scott.simmons27-Jan-05 5:15 
GeneralRe: VB.NET Version &amp; Improvements Pin
unfriendlyboy29-Jan-05 17:51
unfriendlyboy29-Jan-05 17:51 
GeneralRe: VB.NET Version &amp; Improvements Pin
Paul Russo21-Jun-06 1:41
Paul Russo21-Jun-06 1:41 

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.