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 the case. Another team, or a utility such as the Web Services Description Language Tool (Wsdl.exe), may create the class—and you have only the binary assembly. 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));
'Usage
Dim emailAddressValidator As Validator(Of String) _
= New RegexValidator("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
Dim shortStringValidator As Validator _
= 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 the parameter "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*". The variable emailAddressValidator contains the reference to this instance. The second line uses new to create an instance of the AndCompositeValidator class. The variable shortStringValidator contains the reference to this instance. You can use the AndCompositeValidator class to create a composite validator. In this example, the composite validator contains a NotNullValidator instance and a StringLengthValidator instance.
After you programmatically create a Validator object, you can use the Validate method to validate an object as described in Validating an Object.