berserk.org

berserk.org header image

Custom highlight validators in ASP.NET / C#

October 31st, 2005 · No Comments

[Normal view of the label/textfield]

[Failed validation view of label/textfield]

[Validation Summary showing accompanying error message.]

I figured I’d share a snippet of code that shows how to make a custom ASP.NET validator that I’ll call a HighlightRangeValidator.

Using this Validation scheme has a three part commitment. The idea here is to create pairs of controls. One will be a label, the other will be your control. The third piece will of course be your validator.

You will pass in the pair to your validator as ‘controlToValidate’ and ‘affectedControl’. When validation fails you can have a CSS style put onto your label that will help give the user a visual indication of where an error needs to be fixed.

[You can just view the images above to get the idea ]

So how do we do this? Read on and find out.

C# code

The first thing we’ll tackle is creating our new custom validator. This is done by sub-classing the appropriate Validator super class. In this example we are going to sub-class RangeValidator (you can do this with any of the other validator types to achieve the same effect).


using System;
using System.Text;
using System.Collections;
using System.Web.UI.WebControls;

namespace Foo.Bar.Validators {
	/// <summary>
	/// A custom RangeValidator control that will highlight an "affected control"
	/// with an error CSS class to give the user a visual marker for input   that needs
	/// fixing.
	/// </summary>
	public class HighlightRangeValidator : RangeValidator {

        String affectedControl = "";
        String affectedControlCSSClass = "errText";

        protected override bool EvaluateIsValid() {
            bool retVal = base.EvaluateIsValid();

            WebControl afc = (WebControl)this.FindControl( AffectedControl );
            //
            //  Remove any modifications just in case we've done them before.
            //
            if ( afc != null ) {
                afc.Attributes.Remove( "class" );
                afc.ToolTip = "";
            }

            if ( !retVal && afc != null ) {
                afc.Attributes.Add( "class", AffectedControlCssClass );
                afc.ToolTip = ErrorMessage;
            }
            return retVal;
        }

        public String AffectedControl {
            get {
                return affectedControl;
            }
            set {
                affectedControl = value;
            }
        }

        public String AffectedControlCssClass {
            get {
                return affectedControlCSSClass;
            }
            set {
                affectedControlCSSClass = value;
            }
        }
    }
}

ASPX code

Now we get to use the new validator in our .aspx file.

The first thing you’ll need to do is register where your validators are. In this sample the project dll that is created is called Foo.dll, I’ve chosen ‘cv’ for the prefix, and have given the appropriate namespace.

<%@ Register TagPrefix=”cv” Namespace=”Foo.Bar.Validators” Assembly=”Foo” %>

Next we define our control “pair”:

<asp:label id=”lblSignedCopies” runat=”server”>Signed</asp:label>:</td>
<asp:textbox id=”signedCopies” runat=”server” columns=”8″>Signed</asp:label>:</td>

Finally, our custom validator. Note the controlToValidate and affectedControl values.

<cv:HighlightRangeValidator id=”vSignedCopies” runat=”server” controlToValidate=”signedCopies” errormessage=”Signed copies must be an integer from 0 to 99.” affectedControl=”lblSignedCopies” minimumvalue=”0″ maximumvalue=”99″ type=”Integer” cssclass=”errText”/>

NOTE: Here is the .errText CSS for reference:

.errText {
background-color: #990000;
color: #FFFFFF;
font-family: verdana, helvetica, sans-serif;
padding: 2px;
margin-top: 2px;
margin-bottom: 2px;
}

update: Here’s a Visual Studio 2003 zip including a custom library and a minimal http://localhost/validators/ website.

Tags: code