Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Details of Creating Validators Programmatically

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

Using attributes to create rule sets is only possible if you have the source code for the class that you want to validate. In some cases, this may not be true. Another team may write the class, you may only have the binary assembly, as in the case of a .NET Framework class, or a utility such as the Web Services Description Language Tool (wsdl.exe) may generate the class. This means that you cannot use the ValidationFactory class to obtain a reference to the Validator object.

Instead, another option is to create validators programmatically. This is shown in the following code example:

Validator<string> emailAddressValidator = new RegExValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

Validator shortStringValidator = 
new AndCompositeValidator(new NotNullValidator(),
new StringLengthValidator(1, 5));

In this example, the first line uses new to create an instance of the RegExValidator class with argument "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*". The variable emailAddressValidator contains the reference to the class. The second line uses new to create an instance of the AndCompositeValidator class. The variable shortStringValidator contains the reference to the class. You can use the AndCompositeValidator class to create a composite validator. In this case, the composite validator contains a NotNullValidator object and a StringLengthValidator object.

Once you have created a Validator object programmatically, you can use the Validate method to validate an object as described in Validating an Object.

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.
Show:
© 2015 Microsoft