Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Validation with Enterprise Library 3.x

Usually object validation requires writing a lot of code that examines properties and returns validation result. With VAB this scenario becomes extremely easy and simple. Let us consider sample class:

    1 public class User

    2 {

    3   public User()

    4   {

    5   }

    6 

    7   private string _firstName;

    8   public string FirstName

    9   {

   10     get { return _firstName; }

   11     set { _firstName = value; }

   12   }

   13 

   14   private string _lastName;

   15   public string LastName

   16   {

   17     get { return _lastName; }

   18     set { _lastName = value; }

   19   }

   20 }

Now let’s assume some validation rules we want to fill: # First name is required # Last name is required # First name can’t be longer than 20 characters To complete that task we probably would write something like this:

    1 public List<string> Validate()

    2 {

    3   List<string> validationResults = new List<string>();

    4   if (string.IsNullOrEmpty(FirstName))

    5   {

    6     validationResults.Add("FirstName is required");

    7   }

    8   if (!string.IsNullOrEmpty(FirstName) && FirstName.Length > 20)

    9   {

   10     validationResults.Add("FirstName can not be longer than 20 characters");

   11   }

   12   if (string.IsNullOrEmpty(LastName))

   13   {

   14     validationResults.Add("LastName is required");

   15   }

   16   if (validationResults.Count > 0)

   17   {

   18     return validationResults;

   19   }

   20   else

   21   {

   22     return null;

   23   }

   24 }

And this is the code that validates the class.

    1 static void Main(string[] args)

    2 {

    3   User myUser = new User();

    4   myUser.FirstName = "Very very long first name";

    5 

    6   List<string> validationResults = myUser.Validate();

    7   if (validationResults != null)

    8   {

    9     Console.WriteLine("Validation errors:");

   10     foreach (string result in validationResults)

   11     {

   12       Console.WriteLine(result);

   13     }

   14   }

   15   else

   16   {

   17     Console.WriteLine("Validation ok!");

   18   }

   19   Console.ReadLine();

   20 }

There is many ways to code validation so it can look very different for each of us. However one thing will remain less or more the same - property examination. This piece of code will grow with number of properties. How VAB can help there. The best will be to take a look to code sample below. This code is doing the same validation as previous one.

    1 public class User

    2 {

    3   public User()

    4   {

    5   }

    6 

    7   private string _firstName;

    8   [NotNullValidator(MessageTemplate="First Name is required")]

    9   [StringLengthValidator(1, 20, MessageTemplate="First name can not be longer that 50 characters")]

   10   public string FirstName

   11   {

   12     get { return _firstName; }

   13     set { _firstName = value; }

   14   }

   15 

   16   private string _lastName;

   17   [NotNullValidator(MessageTemplate = "First Name is required")]

   18   public string LastName

   19   {

   20     get { return _lastName; }

   21     set { _lastName = value; }

   22   }

   23 }

That code requires reference to Microsoft.Practices.EnterpriseLibrary.Validation.dll and two extra lines on top:

    1 using Microsoft.Practices.EnterpriseLibrary.Validation;

    2 using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

The consuming code will be almost the same as in previous case:

    1 static void Main(string[] args)

    2 {

    3   User myUser = new User();

    4   myUser.FirstName = "Very very long first name";

    5 

    6   ValidationResults results = Validation.Validate<User>(myUser);

    7   if (!results.IsValid)

    8   {

    9     Console.WriteLine("Validation errors:");

   10     foreach (ValidationResult result in results)

   11     {

   12       Console.WriteLine(result.Message);

   13     }

   14   }

   15   else

   16   {

   17     Console.WriteLine("Validation ok!");

   18   }

   19   Console.ReadLine();

   20 }

I think that after that example all is clear, validation has been added to properties as attributes. VAB provides number of validation attributes. List of all of them is too long to put it there so let me list a few most popular:

  • ContainsCharactersValidator - Performs validation on strings by verifying if it contains a character set.
  • DateTimeRangeValidator - Performs validation on DateTime instances by comparing them to the specified boundaries.
  • NotNullValidator - Logs a failure when validating a nullNothingnullptr reference.
  • RangeValidator - Performs validation on T instances by comparing them to the specified boundaries.
  • RegexValidator - Performs validation on strings by matching them to a Regex.
  • StringLengthValidator - Performs validation on strings by comparing their lengths to the specified boundaries.

And of course you can create your own validation method for some complex criteria and use that in the same way.

Example I shown is very simple presentation of the idea behing validation in Enterprise Library implementation. How far this will go depend only on what wee need. Validation can be also connected with Policy Iniection Application Block but this is another topic. 

Michal Grzegorzewski is actually wrtiting a bigger article about Validation Application Block. Stay tuned and watch his blog if you want a bit more details.

Hope that help

kick it on DotNetKicks.com

Posted 06-26-2007 12:43 PM by Jimmy

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)