Validation Application Block in Enterprise Library 3.0 - Using Validation Facade Class - Part I
by David Hayden ( Microsoft MVP C# ), Filed: Enterprise Library 3.0 Tutorials
I had a chance last night to play with the Validation Application Block in Enterprise Library 3.0. The block felt very natural to me, because 1) the Validation Application Block follows the same patterns as all the other blocks, and 2) I have been using attribute-based validation of class members for several years now.
Using ValidatorAttributes to Decorate Class Members
Taking a very simple case, you can decorate the members of your classes with ValidatorAttributes to help validate your business classes.
public class Subscriber
{
private string _name;
[NotNullValidator]
[StringLengthValidator(1,200)]
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _emailAddress;
[NotNullValidator]
[EmailAddressValidator]
public string EmailAddress
{
get { return _emailAddress; }
set { _emailAddress = value; }
}
public Subscriber() {}
}
The Validation Application Block comes with a number of ValidatorAttributes that you can use to decorate your class members. I used the NotNullValidatorAttribute, StringLengthValidatorAttribute, and a custom validator I created myself, called EmailAddressValidatorAttribute.
Validating Business Object Using the Validation Facade Class
Again, taking a simple case, you can validate an instance of Subscriber using the Validation Facade Class that is a part of the Validation Application Block.
// Create subscriber with bad email address
Subscriber subscriber = new Subscriber();
subscriber.Name = "David Hayden";
subscriber.EmailAddress = "bademail.com";
// Validate subscriber using facade
ValidationResults results = Validation.Validate(subscriber);
// Check if valid
if (!results.IsValid)
{
// If not valid, loop through the ValidationResults...
foreach (ValidationResult result in results)
Console.WriteLine(string.Format("Key: {0},
Message: {1}", result.Key.ToString(), result.Message));
Console.ReadLine();
}
Note if you are just using attributes to validate classes and nothing is in the configuration file, you can use an alternative Validation Facade Class Method that just looks at attributes to avoid the creation of an IConfigurationSource that essentially has nothing in it with regards to the validation of the classes. This would be the ValidateFromAttributes method
ValidationResults results = Validation.
ValidateFromAttributes<Subscriber>(subscriber);
Conclusion
This is one way to use the Validation Application Block. Simply add ValidatorAttributes to your classes and use the Validation Facade Class to validate them. In future tutorials, I will look at other ways to use the Validation Application Block.
by David Hayden ( Microsoft MVP C# )
Filed: Enterprise Library 3.0 Tutorials