Using Configuration-Based Validation
All the examples so far have shown the steps involved in using validation attributes directly from within code. Obviously, this approach has a drawback: Every time the validation logic changes, you must modify the code, recompile it, and redeploy it. In addition, reusing attributed validation code is not straightforward. To address these issues, the Validation Block lets you use configuration-driven validation where you specify the validation behavior in an external configuration file, such as
app.config or
web.config. Because the validation behavior specification is external to the application, this approach is considerably more flexible and can be ported to other applications more easily.
The simplest way to create a configuration file for use with the Validation Block is to leverage the Enterprise Library Configuration Tool (available via the Start—> Programs—> Enterprise Library 3.0 - April 2007 menu option). For the purposes of this example, consider a simple Department class for which you'll specify validation behavior through the configuration tool. Here's the Department class code:
using System;
namespace ValidationExample
{
public class Department
{
private string name;
private string description;
public string Name
{
get { return name; }
set { name = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
}
}
The Department class has two properties
Name and
Description. Now add a validation rule for the
Name property to validate that the value supplied is between 1 and 50 characters. Here are the steps:
- Launch the Enterprise Library configuration tool. Select File—> New Application from the menu.
- Right click on the Application Configuration node and select New—> Validation Application Block from the menu.
- Right click on the Validation Application Block node and select New—> Type from the menu. You'll see the Type Selector dialog box.
- Click on the "Load an Assembly" button and select the name of the assembly that contains the Department class.
- You'll see a "Type Select" dialog containing a list of classes in the assembly. Select the Department class from the list and click OK.
- Right click on the Department class and select New—> Rule Set from the menu. Change the default rule from "Rule Set" to "DepartmentDefaultRuleset."
 | |
Figure 2. Configuring Validation in an Application Configuration File: You can use the Enterprise Library Configuration tool to create the configuration file and specify validation behavior for your application. |
- Right click on the DepartmentDefaultRuleset node and select New—> Choose Members from the menu. In the Member selector dialog, select the Name property and click OK.
- Right click on the Name node and select New—> String Length Validator from the menu.
- Now set the String Length Validator properties to the following values, as shown in Figure 2:
- LowerBound : 1
- UpperBound : 50
- LowerBoundType : Inclusive
- MessageTemplate : Name should be between 1 and 50 characters
Finally, save the configuration file as
App.config in the root project directory of the Windows Forms application.
Now, if you open the
App.config file in a text editor or in Visual Studio, you should see something similar to the following:
<configuration>
<configSections>
<section name="validation"
type="Microsoft.Practices.EnterpriseLibrary.Validation.
Configuration.ValidationSettings, Microsoft.Practices.
EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<validation>
<type assemblyName="ValidationExample, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null"
name="ValidationExample.Department">
<ruleset name="DepartmentDefaultRuleset">
<properties>
<property name="Name">
<validator lowerBound="1" lowerBoundType="Inclusive"
upperBound="50" upperBoundType="Inclusive" negated="false"
messageTemplate="Name should be between 1 and 50
characters" messageTemplateResourceName=""
messageTemplateResourceType="" tag=""
type="Microsoft.Practices.EnterpriseLibrary.
Validation.Validators.StringLengthValidator,
Microsoft.Practices.EnterpriseLibrary.Validation,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
name="String Length Validator" />
</property>
</properties>
</ruleset>
</type>
</validation>
</configuration>
To test the configuration, you need to invoke the validation rule from code. To do that, add a new button named
btnValidateDepartmentFromConfig and modify its
Click event to look as follows:
private void btnValidateDepartmentFromConfig_Click
(object sender, EventArgs e)
{
Department dept = new Department();
dept.Name = "";
dept.Description = "Production Department";
lstValidationResults.Items.Clear();
ValidationResults results =
Validation.ValidateFromConfiguration(dept,
"DepartmentDefaultRuleset");
//Inspect the ValidationResults object
if (!results.IsValid)
{
//If not valid, loop through the ValidationResults
foreach (ValidationResult result in results)
{
lstValidationResults.Items.Add("Key = " + result.Key);
lstValidationResults.Items.Add("Message = " +
result.Message);
lstValidationResults.Items.Add(".....");
}
}
}
Note the
Validation.ValidateFromConfiguration() method specifically enables you to validate the Department object using the rules supplied in the configuration file. However, you can achieve the same results using the overloaded
Validate() method:
ValidationResults results =
Validation.ValidateFromConfiguration(dept,
"DepartmentDefaultRuleset");
When you call the
ValidateFromConfiguration() method, you can also supply the name of the rule set that identifies the group of validation rules to be applied for the Department class.