Partager via


Creating Validators Programmatically

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.

In addition, you may want to validate individual values, rather than entire objects. For both of these scenarios, you can create validators programmatically. This is shown in the following code example.

Validator<string> emailAddressValidator 
    = new RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
ValidationResults r = emailAddressValidator.Validate(myEmailAddress);

Validator shortStringValidator 
    = new AndCompositeValidator(new NotNullValidator(), new StringLengthValidator(1, 5));
shortStringValidator.Validate(myStringValue, r);
'Usage
Dim emailAddressValidator As Validator(Of String) _
    = New RegexValidator("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
Dim r As ValidationResults = emailAddressValidator.Validate(myEmailAddress)

Dim shortStringValidator As Validator _
    = New AndCompositeValidator(New NotNullValidator(), New StringLengthValidator(1, 5))
shortStringValidator.Validate(myStringValue, r)

In this example, the first line uses new to create an instance of the RegExValidator class with the parameter value set to the @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" regular expression string. 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 the topic Validating Objects. Notice how the second call to the Validate method uses the overload that accepts an existing instance of the ValidationResults class and adds any validation errors it finds to the list.

As an alternative to creating validators by executing the constructor, you can resolve individual validators through the Enterprise Library Container. If you specify a name when you resolve the instance, this is interpreted as the name of the rule set for that validator to use when validating objects. You must add the Validation Block Extension to the container to use this approach.