MSDN Library

Validation Application Block

 

Validation Application Block

patterns & practices Developer Center

Enterprise Library

patterns & practices Developer Center

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Validation Application Block. An application block is reusable and extensible source code-based guidance that simplifies development of common logging functionality in .NET Framework applications.

Contents

Introduction to the Validation Application Block
Design of the Validation Application Block
What's New
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Validation Application Block

Any application that accepts input either from users or from other systems must ensure that the information is valid in terms of some set of rules that you specify. For example, when processing an order, you may need to check that a customer's phone number has the correct number of digits, or that a date falls within a particular range. In addition, if the validation fails, you may need to send an error message that explains what is wrong.

The Enterprise Library Validation Application Block provides a library of classes, called validators, that supplies the code for validating .NET Framework data types. For example, one validator checks for null strings and another validator checks that a number falls within a specified range.

There are also special validators named AndCompositeValidator and OrCompositeValidator. If you create an AndCompositeValidator, which aggregates other validators, all validators in the composite must be true for a successful validation. If you create an OrCompositeValidator, at least one of the validators in the composite must be true for a successful validation.

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.

There are three ways to perform validation within the application block, and to create rule sets. They are:

  • Using configuration
  • Using attributes
  • Using code

In addition, the Validation Application Block includes adapters that allow you to use the application block with the following technologies:

  • ASP.NET
  • Windows Forms
  • Windows Communications Framework (WCF)

Common Scenarios and Goals

Validation has many applications. For example, you can use it to prevent the injection of malicious data by checking to see if a string is too long or if it contains illegal characters. You can also use validation to enforce business rules and to provide responses to user input. It is often important to validate data several times within the same application. For example, you may need to validate data at the UI layer to give immediate feedback when a user enters an invalid data value, and again at the service interface layer for security.

Example Application Code

C#
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
{
    public static void Main() 
    {
        Customer myCustomer = new Customer("A name that is too long");
        ValidationResults r = Validation.Validate<Customer>(myCustomer);
        if (!r.IsValid)
        {
            throw new InvalidOperationException("Validation error found.");
        }
    }
}
Visual Basic
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
Module Module1
    Public Sub Main()
        Dim myCustomer As Customer = New Customer()
        myCustomer.CustomerName = "A name that is too long"
        Dim r As ValidationResults = Validation.Validate(myCustomer)
        If Not r.IsValid Then
            Throw New InvalidOperationException("Validation error found.")
        End If
    End Sub
End Module

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

Highlights

The Validation Application Block has the following benefits:

  • It helps maintain consistent validation practices.
  • It includes validators for validating most standard .NET data types.
  • It allows you to create validation rules with configuration, with attributes, and with code.
  • It allows you to associate multiple rule sets with the same class and with members of that class.
  • It can be integrated with ASP.NET, Windows Forms, and Windows Communications Foundation (WCF).

Design of the Validation Application Block

The Validation Application Block is designed to do the following:

  • Encapsulate the logic used to perform the most common validation tasks into minimal application code.
  • Relieve developers of the requirement to write duplicate code and custom code for common validation tasks.
  • Allow validation rules to be changed after they have been deployed and to ensure that changes happen simultaneously and consistently.

Design Highlights

Figure 1 illustrates the interrelationships between the key classes in the Validation Application Block.

Ff648167.entlib_validationappblock(en-us,PandP.10).gif

Figure 1. Diagram of Validation Application Block

The client code can call the Validation façade, which allows you to create a validator and validate an object with a single line of code. Alternatively, it can call the ValidationFactory class to create a validator and then call the Validate method on the Validator class to perform the check.

The class diagram shows the various kinds of validators and attributes provided by the Validation Application Block. These are described in the previous sections.

What's New

The May 2007 release of the Validation Application Block includes the following improvements:

  • An issue that prevented the PropertyComparisonValidator from working with the Windows Forms integration adapter is fixed in this release.
  • The message template for the PropertyComparisonValidator can now be saved using the configuration tools.

Getting Started

The Validation Application Block has been developed as a result of analyzing common enterprise development challenges and successful solutions to these challenges. However, because each application is unique, you will not find this application block suitable for every application. To evaluate this application block and determine its applicability to your projects, Microsoft suggests you dedicate at least half of a day to explore the application block. The following is a suggested evaluation approach:

  1. Download Enterprise Library.
  2. Install Enterprise Library and compile all application blocks and tools.
  3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
  4. Compile and run the QuickStart samples, and read through the related "QuickStart Walkthroughs" and "Key Scenarios" sections of the documentation.
  5. If the application block looks like a good fit for your application, try implementing a simple use case in your application or in a throw-away prototype application using the application block.

Community

Enterprise Library, like many patterns & practices deliverables, is associated with a community site. On this community site, you can post questions, provide feedback, or connect with other users for sharing ideas. Community members can also help Microsoft plan and test future deliverables, and download additional content such as extensions and training material.

Feedback and Support

Questions? Comments? Suggestions? To provide feedback about this application block, or to get help with any problems, please visit the Enterprise Library Community site. The community site is the preferred feedback and support channel because it allows you to share your ideas, questions, and solutions with the entire community.

Enterprise Library is a guidance offering, designed to be reused, customized, and extended. It is not a Microsoft product. Code-based guidance is shipped "as is" and without warranties. Customers can obtain support through Microsoft Support Services for a fee, but the code is considered user-written by Microsoft support staff. For more information about our support policy, see the Enterprise Library home page.

Related Titles

Start | Previous |

patterns & practices Developer Center

Show:
© 2016 Microsoft