Validation Application Block
How many hours during the day do you sit around and write validation code? Way to many to count, if I'm reading your mind. Validation is pretty common it's in usage that it occurred to me that I needed some sort of compact way of encapsulating rules and business logic. So on my train ride home, I thought to myself -- "Gee, I guess I could create validation attributes, and decorate my properties!" I really thought I was brilliant, and somewhat innovative, but lo and behold, I get home and discover there's already an application block written for just that purpose. So I'm going to entertain myself by writing a use case for this, and post code at the end.
Here's the beauty of the application block: It's flexible. You can decorate your class entities with validation attributes, or validate primitive data types or objects. You can also set up rules via XML, and there's support for ASP.NET, Windows Forms and WCF.
Here's what we would do traditionally:
if (String.IsNullOrEmpty(Textbox1.Text))
{
throw new ArgumentNullException("No text specified!!");
} else {
Foo f = new Foo();
f.bar = TextBox1.Text;
}
Here's how we can solve that with the VAB in code:
StringValidator v = new StringValidator(1, 10); v.Validate(Textbox1.Text); //validator would blow up if invalid.. and not execute the next line Foo f = new Foo(); f.bar = Textbox1.Text;
Here's an alternative way by decorating the property with an attribute:
public class Foo
{
[StringLengthValidator(1, 50)]
public string bar
{
get;set;
}
}
This is a very simple usage pattern for what the block can really do; there are Validators that can compare dates, enums and even perform regular expressions. Additionally, you can write you own custom validators, and define more finite rules either inline or using configuration files via XML. It really depends on your business requirements and how crazy you want to extend it. But the point is, you no longer need to stick logic in your website tier.. there's already a framework available that should save your some time.
Here's more information on VAB:
http://msdn.microsoft.com/en-us/library/dd140088.aspx
Download FAB; You can get it as part of the entire Enterprise library that Microsoft releases every now and then:
http://msdn.microsoft.com/en-us/library/cc467894.aspx
You can download my sourcecode example here. Basically the example is a webform for entering your pet information, it performs validation via inline code and makes use of validation attributes. I'm using the Enterprise Library 3.1 - May 2007 version, only because I need .NET framework 2.0 support.
Happy Coding.

0 Comments