Practical ASP.NET

Validators: The Easy Way To Build Business Rules into Your UI

Validator controls make handling errors and reporting them in the UI easy, but what you may not know is how easy it is to create your own Validator.

Validators are terrific controls but the ones that come with ASP.NET are, well, limited. For most business logic, developers either use the CustomValidator (which lets you insert your own validation code) or bypass the Validator controls altogether which means writing a lot of code that Validators take care of automatically. The right answer is often to create your own Validator to call the validation code in your application.

I had one client who must have collected address information on a dozen pages on several different sites. Since adding the necessary controls and code to all of these pages was really boring, I considered creating an "address user control" that I could drag onto any page. However, user controls can only be used in one project (besides, the client wanted the various controls laid out in different ways on different pages). Instead, I created a new Validator -- the AddressValidator -- and put it in the Toolbox so I could use it on any page in any site.

I've picked the AddressValidator control for this example because it supports checking multiple controls (not just the StreetAddress but also the City, Province/State, Country controls) which might be text boxes or some kind of listing control (drop-down list, radio button lists). This lets me not only show how to handle multiple controls but also to how to list controls in the Properties window.

Creating the Control
Creating a Validation control is relatively straightforward: Create a new project and, from the Web tab, select ASP.NET Server Control (I named my project "PHVValidators"). Once the project is created, rename the default ServerControl1.cs file to the name you want for your control (I used "AddressValidator") and have the class inherit from BaseValidator. You'll also need to change the name of the control in the ToolboxData attribute that appears on the class declaration:

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PHVValidators
{
  [DefaultProperty("ControlToValidate")]
  [ToolboxData("<{0}:AddressValidator runat=server>
              </{0}:AddressValidator>")]
   public class AddressValidator : 
                    System.Web.UI.WebControls.BaseValidator
 {

All you need to add to the BaseValidator is a test for valid data and any additional properties required to support your validation code.

I'll look at the properties first. For them, I need some fields to hold the names of the controls holding the parts of the address. I also need some properties to capture and hold that data. Since these properties must be set to the name of a control on the page, I'd like to have the property in the Properties window display a drop list of controls on the page. That's easy to do: I just add the TypeConvererAttribute attribute to the property, passing the type of the ValidatedControlConverter. Here's an example of the property to hold the name of the control that with the name of the city:

string cityId = "";

[TypeConverterAttribute(typeof(ValidatedControlConverter))] _
 string CityId
{
    get
   {
       return cityId;
   }
   set
  {
      cityId = value;
   }
}

Validating Data
The only method in the BaseValidator class you must override is the EvaluateIsValid method and return true or false, depending on the result of your test To get the values of controls on the page, call the built-in GetControlValidationValue method passing the name of the control that you want. This code retrieves the value of the control whose name was set in the CityId property and returns false to indicate a failed test if the control is empty:

protected override bool EvaluateIsValid()
{
 string CityValue = this.GetControlValidationValue(this.CityId);
 if (CityValue == "")
 {
   return false;
 }
 return true;
}

In real life, you'd probably call validation methods built into your middle-tier business objects to check your data.

To test your Validator, just add a Web project to the Solution you created for your Validator control. Your new Validator will appear at the top of the Toolbox -- you can drag it onto the page, set your properties and debug your code. If you make a change to your Validator control, you'll have to rebuild your solution, delete the control from the page, and drag it back onto the page from the Toolbox.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube