Click here to Skip to main content
Click here to Skip to main content
Go to top

Introduction to the Validation Application Block

, 2 Feb 2007
Rate this:
Please Sign up or sign in to vote.
Validation application block has been added to enterprise library 2007 CTP release

Validation application block has been added to enterprise library 2007 CTP release. You can download it from here.

Introduction

Any application that takes input from a user or other system must ensure that the information is in the correct format, in terms of some rules that specify in several ways, like a registration form has lots of field like social security number, credit card, email has some specific format demand validation check before inserting to database. In addition, if the validation fails, usually 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 that strings are not null and another validator ensures that a number falls within a specified range. You can use a Boolean AND or OR to create composite validators. You can also create groups of validators. A group of validators is called a rule set, although a rule set may contain as few as a single validator. A rule set is a way 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.

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

  • ASP.NET
  • Windows Forms
  • AJAX
  • Windows Communications Framework (WCF)
  • Windows Presentation Framework (WPF)

To get more detailed information, check Validation Application Block documentation that comes with this release.

How to Use Validation Application Block in your Application

Open application configuration file app.config or web.config by Enterprise Library Configuration tools.

Follow the below steps to add the Validation Application Block:

  1. Start the Enterprise Library Configuration Console. To use the configuration console, click Start, point to All Programs, point to Microsoft patterns & practices, point to Enterprise Library 3.0 – January 2007 CTP, and then click Enterprise Library Configuration.
  2. Click the Open Existing Application icon and located your config file... Open application configuration file app.config or eb.config by Enterprise Library Configuration tools.

Right-click Application Configuration, point to New, and then click Validation Application Block.

Enlib1.JPG

Applying Validators at the Type Level

The following procedure shows how to apply validators at the type level.

To apply validators at the type level:

  1. Right-click on Validation Application Block, point to New and click Type.

    Enlib2.JPG

  2. The Type Selector — System.Object dialog box opens.
  3. Double-click on the assembly you want to use. If the assembly is not in the dialog box, click Load Assembly and navigate to it.

    Enlib3.JPG

  4. Double-click on the type you want to validate.
  5. (Optional) If there is an existing rule set you want to specify as the default, click on DefaultRule in the right pane and select it from the dropdown box.
  6. To define a rule set, right-click on the type node, point to New and click Rule Set.
  7. Right-click on Self, point to New, and click the validator you want to use. Typically this is either Custom Validator or Not Null Validator.

    Defining a Rule Set for a Specific Type

    The following procedure shows how to define a rule set for a specific type. Note that it is possible for an object to have multiple rule sets associated with it.

    To define a rule set for a specific type:

  8. Right-click on Validation Application Block, point to New and click Type.
  9. The Type Selector — System.Object dialog box opens.
  10. Double-click on the assembly you want to use. If the assembly is not in the dialog box, click Load Assembly and navigate to it.
  11. Double-click on the type you want to validate.
  12. (Optional) If there is an existing rule set, you want to specify as the default, click on DefaultRule in the right pane and select it from the dropdown box.
  13. To define a rule set, right-click on the type node, point to New and click Rule Set. Note that a rule set can contain as few as one validator.
  14. (Optional) Enter the name of the rule set in the right pane.
  15. To select what you want to validate, right-click on Rule Set, point to New, and select Field, Method or Property.

    Enlib4.JPG

  16. (Optional) Enter the name of the field, method or property in the right pane.
  17. Right-click on the field, method or property and select the validator you want to apply to it.
  18. (Optional) Fill in the Tag, MessageTemplate, and MessageTemplateResource fields, as appropriate. You can either enter the MessageTemplateResourceTypeName field or click on the ellipsis and use the Type Selector — System.Object dialog box to select it. Many validators also have fields that are specific to them. Fill these out as well.
  19. Repeat steps 10 and 11 for each validator you add. Applying Validators to Type Members. The following procedure explains how to apply validators to type members. Type members include properties, methods and fields.

    Enlib5.JPG

    To apply validators to type members:

  20. Right-click on Validation Application Block, point to New and click Type.
  21. The Type Selector — System.Object dialog box opens.
  22. Double-click on the assembly you want to use. If the assembly is not in the dialog box, click Load Assembly and navigate to it.
  23. Double-click on the type you want to validate.
  24. (Optional) If there is an existing rule set you want to specify as the default, click on DefaultRule in the right pane and select it from the dropdown box.
  25. To define a rule set, right-click on the type node, point to New and click Rule Set.
  26. (Optional) Enter the name of the rule set in the right pane.
  27. Right-click on Rule Set, point to New, and select Choose Members.
  28. The Member Selector dialog box appears.
  29. Click Properties, Methods and/or Fields, depending on what you want to validate. This selects all the entries.
  30. Deselect the properties, methods and/or fields you do not want to validate. Click OK. The desired validators appear in the configuration hierarchy.
  31. Right-click on the field, method or property and select the validator you want to apply to it.
  32. For each validator, fill in the Tag, MessageTemplate, and MessageTemplateResource fields, as appropriate. You can either enter the MessageTemplateResourceTypeName field or click on the ellipsis and use the Type Selector — System.Object dialog box to select it. Many validators also have fields that are specific to them. Fill these out as well.
  33. Repeat Steps 10 through 14 for each member and validator you add.

    Enlib6.JPG

Defining Composite Validators

The following procedure explains how to define composite validators. Composite validators are built from individual validators that are combined with a Boolean AND or OR.

To define composite validators:

  1. Right-click on the type or type member you want to validate.
  2. Select either AndCompositeValidator or OrCompositeValidator.
  3. Right-click on AndCompositeValidator or on OrCompositeValidator and select one of the validators that will be a part of the composite validator. Fill out the fields in the right pane. Repeat this step for each validator you add.

See more in the release documentation.

Now have a look at some simple code:

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

namespace ValidationApplicationBlock
{
    public class StringValidator
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public StringValidator()
        {
        }
        /// <summary>
        /// Validation 
        /// </summary>
        [NotNullValidator]    
        [StringLengthValidator(1, 50)]    
        public string Name;    
        
    }
}

StringValidator oStringValidator = new StringValidator();
oStringValidator.Name = txtName.Text; //get the value from use
 
ValidationResults r = Validation.Validate(oStringValidator);
if (!r.IsValid)
   {
    errorProvider1.SetError(txtEmail, 
	"Input Not Vail"); //showing error description using error provider
   }

Really cool and simple.

Using the Validation Façade

In most situations, you can take advantage of the Validation façade. This class allows you to create a Validatorinstance and validate an object with a single line of code. This is shown in the following code example:

Customer myCustomer = new Customer( /* ... */ );
ValidationResults r = Validation.Validate(myCustomer);

This code is equivalent to the following code example:

Customer myCustomer = new Customer( /* ... */ );
Validator<customer> v = ValidationFactory.CreateValidator<customer>();
ValidationResults r = v.Validate(myCustomer);

You will find more details about Façade pattern here.

Using Self Validation

[HasSelfValidation]
public class MaXMin
{ 
    private int min; 
    private int max;
 
    // ...

    [SelfValidation]             
    public void Check (ValidationResults results) 
    { 
         if (max < min) 
           results.AddResult(new ValidationResult
		("Max less than min", this, null, null, null));
    } 
}

Ruleset

Sometimes, you need to only care for some specific property then create a Ruleset that distinguishes the null rules separate from the others farther. This can be checked by using Validation.Validate(subscriber, "UserInfo");

public class UserInfo
{
    private string name;

    [NotNullValidator(Ruleset="UserInfo")]
    [StringLengthValidator(1,200)]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private string emailAddress;

    [NotNullValidator(Ruleset="UserInfo")]
    [EmailAddressValidator]
    public string EmailAddress
    {
        get { return emailAddress; }
        set { emailAddress = value; }
    }

    public UserInfo () {}
}

Conclusion

I hope this gives some idea about what is coming within this block. It's not fully decided how Microsoft is going to design this block in case off Ajax and WCF I found in some blogs about this issue. Let's see and wait how it will come…hope this block will also be widely used like data access application block.

Related blogs about validation application block can be found here and here.

History

  • 2nd February, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

n_ahid
Web Developer
Bangladesh Bangladesh

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberjmzl6665-Feb-10 15:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 2 Feb 2007
Article Copyright 2007 by n_ahid
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid