Using configuration for validation

Topics: Validation Application Block
May 24, 2010 at 8:32 AM


In order to keep my web.config nice and clean, I've chosen to keep my validation in a separate configuration file. How do I load this file and use it to validate? I am not interested in using attributes.

My code has got me nowhere.

 Book book = new Book();

book.Title = "asdasdasdaa";

var config = new FileConfigurationSource(@"C:\ValidationRules.config");

ValidationResults results = Validation.ValidateFromConfiguration(book, "RuleSet1");

As you can see, I'm finding it hard to connect the file configuration to actually validating something.

Also as a side question, Do I need unity to use the Validation API?


May 24, 2010 at 8:57 AM
Edited May 24, 2010 at 8:58 AM

You'll use the ValidationFactory.CreateValidator which accepts an instance of IConfigurationSource.  It returns a Validator object on which you can call the Validate method and return a ValidationResults object.

If you're also going to be using that validation configuration for the entire applicaton's validaton rules, you can use .NET's configSource attribute in your configuration file.  However, this only takes a relative phsyical path.

<validation configSource="ValidationRules.config" />

For more information on these 2 approaches, you can refer to Tom Hollander's blog :

And on your second question, no, you need not use Unity.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.

May 24, 2010 at 10:22 AM

Thanks for your quick reply Sarah, It works now.

Just a followup question, is it better to construct Validator objects as you need them or have a static copy to use for all requests relating to that type of object?

Is it better for this line to be static?

Validator val = ValidationFactory.CreateValidator(typeof(Book), "RuleSet1", config);


May 24, 2010 at 10:36 AM

I think the call to CreateValidator is not an expensive call so you can opt to create them just as needed.  Besides, VAB performs caching of validators.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.

May 24, 2010 at 11:00 AM

Thanks again :)