Partager via


What Does the Validation Application Block Do?

Unlike many other validation mechanisms and libraries, which use separate validation controls to validate individual UI elements such as text boxes, the Validation Application Block is designed to allow you to easily validate instances of objects. This means that you can execute validation at any point in your application, and repeat it when required. For example, you can validate an instance of a class populated with values from the UI, validate an instance of the class populated with values received from a Web service, and validate an instance of the class as it passes between layers of your application.

The block provides a library of classes named validators, which implement functionality for validating .NET Framework data types. You can also group validators together in a rule set. A rule set allows you to validate a complex object or graph by composing different validators of different types and applying them to elements in the object graph. Examples of these elements include fields, properties, and nested objects.

You configure validation requirements for specific classes by defining the set of validators and the rules to apply when validating parameter and property values for instances of that class. Then, in many situations, you can validate an instance of the class with a single line of code.

You can define validation rules and carry out validation in the following ways:

  • By using configuration to define rule sets for specific classes. These rules sets are stored in your application configuration file, and can be created using the graphical configuration tools.
  • By adding attributes to members of your classes to define individual rules for public, readable parameters and properties that specify rule sets or individual validation rules. These may be attributes defined within the Validation Application Block that directly target the validators provided with the block, or .NET Data Annotation attributes. The Validation Application Block works with both of these types of attributes.
  • By adding code to your classes that perform self validation of the object parameters or properties. This is a useful way to implement very complex validation rules that depend on the environment or external factors.
  • By using code to create instances of validators and then execute validation on demand.

Note

The Validation Application Block only applies rules specified for the return values for public methods that have no parameters. To validate parameters when a method is invoked, or to validate return values for methods that accept parameters, you can use The Validation Handler. This handler validates parameter values based on the rules for each parameter's type and any validation attributes on the parameters themselves.

The Validation Application Block contains a wide variety of validators, and you can easily create custom validators yourself for your own specific scenarios. As examples of the validators, the block includes a validator that checks for null strings and another validator that checks whether a number falls within a specified range. There are also special validators named the And Composite****Validator and the Or Composite Validator. If you create an And Composite Validator, which aggregates other validators, all validators in the composite validator must return true for successful validation. If you create an Or Composite Validator, at least one of the validators in the composite validator must return true for successful validation.

The Validation Application Block also includes adaptors that you can use in your application UI that support the same type of implementation as ASP.NET, Windows Presentation Foundation (WPF), and Windows Forms validation controls to provide feedback and information to users when validation errors occur. In addition, the block includes an adapter that makes it easy to use in WCF applications.

Example Application Code

The following is a simple example that associates a validator with an object and then validates that object. It assumes that you will resolve the MyExample class through the Unity container to inject an instance of the Validation Application Block ValidatorFactory class.

The code creates a new Customer object and validates it using the Validation Application Block facade. Because the string length validator attribute is applied, the block checks that the length of the customer name is between 0 and 20 characters. In this case, the customer name is illegal because it is too long. The application throws an exception that notifies you of the error.

using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
  [StringLengthValidator(0, 20)]
  public string CustomerName;
    
  public Customer(string customerName)
  {
    this.CustomerName = customerName;
  }
}

public class MyExample
{
  private ValidatorFactory factory;

  public MyExample(ValidatorFactory valFactory)
  {
    factory = valFactory;
  }

  public void MyMethod()
  {
    Customer myCustomer = new Customer("A name that is too long");
    Validator<Customer> customerValidator 
                        = factory.CreateValidator<Customer>();

    // Validate the instance to obtain a collection of validation errors.
    ValidationResults r = customerValidator.Validate(myCustomer);
    if (!r.IsValid)
    {
      throw new InvalidOperationException("Validation error found.");
    }
  }
}
'Usage
Imports Microsoft.Practices.EnterpriseLibrary.Validation
Imports Microsoft.Practices.EnterpriseLibrary.Validation.Validators
Public Class Customer
  <StringLengthValidator(0, 20)> _
  Public CustomerName As String
  Public Sub Customer(ByVal customerName As String)
    Me.CustomerName = customerName
  End Sub
End Class

Public Class MyExample
  Private factory As ValidatorFactory
  
  Public Sub New(ByVal valFactory As ValidatorFactory)
    factory = valFactory
  End Sub
    
  Public Sub MyMethod()
    Dim myCustomer As New Customer("A name that is too long")
    Dim customerValidator As Validator(Of Customer) _
                             = factory.CreateValidator(Of Customer)()
        
    ' Validate the instance to obtain a collection of validation errors.
    Dim r As ValidationResults = customerValidator.Validate(myCustomer)
    If Not r.IsValid Then
      Throw New InvalidOperationException("Validation error found.")
    End If
  End Sub
End Class