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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube