Using the Enterprise Library Validation Application Block in ASP.NET

 

©2007 Alex Homer, Stonebroom Limited, http://www.stonebroom.com

This article shows how you can take advantage of the validation features within the Validation Application Block, part of version 3.0 of Enterprise Library, in your ASP.NET applications. The block supports both UI and object validation, and you can combine these approaches using the same rules if you wish. The ability to validate objects is particularly useful when working with instances that may be generated locally, exposed by other tiers of your application, or received from a remote Web Service.

Contents

Introduction. 1

The Validation Application Block Built-in Validators 3

Configuring Validation Rule Sets 4

Specifying the Target Object Type. 4

Creating a Rule Set and Adding Validators 5

Using Composite Validators 7

Using Validation Rule Sets in ASP.NET. 7

Validating Object Instances 9

The Validate Method. 10

Displaying the Validation Results 11

Validating Objects from Other Sources 12

The Example Web Service. 12

Validating Objects from the Example Web Service. 13

UI Validation Integration in ASP.NET. 15

The PropertyProxyValidator Control 16

Implementing UI Validation in the Example Application. 18

Validating the UI Control Values 18

Accessing PropertyProxyValidator Controls in Code. 19

Summary. 20

Introduction

ASP.NET includes a series of built-in validation controls, integrated with Visual Studio 2005 and Visual Web Developer 2005 Express Edition (VWD), that you can easily incorporate into your Web applications. The validation controls link to existing data entry controls, such as text boxes and list boxes, providing a great client-side user experience while still ensuring that validation also occurs server-side (to protect against spoofing attacks) when the user submits the page.

So, why would you consider using any other type of validation mechanism? The answer depends on what you actually need to validate, where it comes from, and how you want to manage the validation process. Validation within the UI is fine if you are collecting values directly from users, but you may need to do more. For example, you may need to validate object instances that you:

The ASP.NET validation controls are of limited use in these situations. In addition, the parameters for the validation (such as the maximum and minimum values, regular expressions, and other data) for each validated control must reside within the control declarations, or you must set them dynamically at runtime from some other stored configuration source (such as the <appSettings> section of Web.config).

An alternative approach is to make use of the wide-ranging and powerful features of the Validation Application Block. This is part of Enterprise Library version 3.0, from the Microsoft patterns & practices group. The Validation Application Block provides a comprehensive series of validation components that you can apply through configuration, or through attributes applied directly to classes, class members, plus UI controls for use in both ASP.NET and Windows Forms applications.

One of the major advantages with this approach is that you can define rule sets within your application configuration file, with each rule set defining the types of validation to undertake and the individual parameters for that validation process. This means that administrators can quickly and easily change the validation rules and parameters without requiring any changes to the existing code - avoiding the risk of code errors, recompilation issues, and application downtime.

You can also create custom validators that validate individual classes or custom types, and integrate these seamlessly with the existing validators. You can even include validation information within your custom classes and types, so that they support self-validation.

In this article, you will see how you can create rule sets and apply them to existing and new instances of objects, and to UI controls in a Web page. For an example of using directly-applied validation attributes within a class, see the article "Using the Policy Injection Application Block in ASP.NET" at http://www.daveandal.net/articles/policy-injection/, which demonstrates the use of the Validation Handler with individual Validation Attributes.

The documentation installed with Enterprise Library 3.0 also contains comprehensive details and examples of how you can use attributes to apply validation rules, how to create custom validators, and how to use self-validation. Once you are familiar with the basic process for creating and using rule sets and the validators from the Validation Application Block, you will find it easy to extend the techniques to implement all kinds of custom validation mechanisms.

The Validation Application Block Built-in Validators

The Validation Application Block contains a wide range of validators that you can use to check almost any type of property or value. The built-in validators include:

The validators have specific properties, depending on the validation process they carry out. However, all of the validators also have some common properties:

Configuring Validation Rule Sets

To create a rule set for an object, you must first create and compile that object. The example application contains a simple class named CompanyDetails (in the EntLibSampleObject project) that exposes six properties: four of type String, one of type DateTime, and one of type Int32. Open the example solution and view the file EntLibSampleObject.cs to see the class definition.

Once you have a target object class, open the configuration file for your application in one of the two Enterprise Library configuration tools – either the Configuration Console (available from the Start menu), or the Configuration Editor integrated within Visual Studio (right-click on the Web.config or App.config, file in the Solution Explorer window and select Edit Enterprise Library Configuration).

Specifying the Target Object Type

In the configuration editor, right click on the application node (the node immediately below the root Enterprise Library Configuration node) and select New, then click Validation Application Block to add the Validation Application Block to your application. Then right-click on the new Validation Application Block node, select New, and click Type. In the Type Selector dialog, click the Load an assembly... button and navigate to the folder containing your target object. Click Open to load this assembly.

The Type Selector dialog now shows a tree view of all the assemblies containing classes that inherit from System.Object, sorted alphabetically. Find your target assembly in the list (collapse nodes in the tree to make it easier) and select the target class to which you want to attach a rule set (see Figure 1).

Figure 1 – Selecting the target class for applying a rule set in the Enterprise Library Configuration Editor

Click OK, and the class appears in the configuration under the Validation Application Block node. Now you are ready to create the rule set.

Creating a Rule Set and Adding Validators

Right-click on the new target object node in the configuration editor, select New, and click Rule Set. Change the name of the rule set as required – you will use the name in your code so you should specify a name that will help you to read and debug your code, especially if you define more than one rule set.

The next stage is to select the members of the target object that you want to validate. Right-click on the new rule set node, select New, and click Choose Members to display a dialog containing all the public members of the target object (see Figure 2). Select the required members and click OK to close the dialog and add these members to the rule set.

 

Figure 2 – Selecting the members of the target class to which you want to apply validators

Alternatively, to add specific members, right-click on the rule set node, select New, and click Field, Method, or Property. This adds a new node to the rule set. Select the new node and change the name to that of the target object's field, method, or property.

You now have a hierarchy that contains the list of members to which you will add validators. For each target object member, right-click on it, select New, and click the type of validator you want to add. As you add each one, use the Properties window in Visual Studio 2005, or the properties list in the right-hand pane of the Configuration Console, to set the properties you require for each validator.

For example, the CompanyAddress property of the CompanyDetails object in the example application has a String Length Validator attached with the following properties set:

Property

Setting

LowerBound

5

LowerBoundType

Inclusive

Negated

False

Tag

CompanyAddressValidator

UpperBound

100

UpperBoundType

Inclusive

MessageTemplate

Company address must be between 5 and 100 characters

 

Figure 3 shows the completed configuration of the example application. You can see the six properties of the target object class, and the validator specified for each one. The Self node, which the configuration tool adds automatically, allows you to specify validators that will operate on objects that carry the SelfValidation attribute. For more details of self validation, see the topic "Using Self Validation" in the "Key Scenarios" section of the Enterprise Library Validation Application Block documentation.

Figure 3The configuration of validators in the example application. The CompanyDetails class has a rule set named ExampleRuleSet that contains the appropriate validator for each property, depending on the value type

Using Composite Validators

The example application implements a simple scenario where there is only one validator on each property of the target class. However, if you need to perform more complex validation, you can use a composite validator to created nested validator groups that implement AND and OR logic.

For example, you can add an And Composite Validator to a property, and then right-click on this validator, select New, and select other validators to place within this AND group. You might choose to use a Not Null Validator and a Type Conversion Validator, which must both return True for the property value to be considered valid.

You can add more than two validators to a composite validator, nest composite validators within other composite validators, and use the Negated property of any validator to reverse its behaviour. It is difficult to conceive of a validation requirement that you cannot meet using these capabilities.

Using Validation Rule Sets in ASP.NET

The example application for this article, which you can download from http://www.daveandal.net/articles/EntLibValidation/, displays textboxes for the six properties of the target object. These are pre-filled with valid values to save you typing then in. If you open the application and click the Create a company using these values... button, without changing any of the values in the text boxes values or the other settings, the code creates an instance of the target class with valid values, performs validation on the object, and displays the property values and the validation result in the page (see Figure 4).

Figure 4The example application creates an instance of the target object, validates its properties, and displays the results

If you now edit the values in the text boxes so that they are outside the range of valid values, and click the Create a company using these values... button again, the page displays a list of errors it encounters when validating the new object instance (see Figure 5). You can see in this case that the CompanyName, CompanyPostalCode, and EmployeeCount properties have invalid values.

Figure 5The result of validating an object with invalid property values

For each invalid property value, the page displays the contents of the MessageTemplate for the validator, the name of the target property, the value of the Tag property of the validator, and the type name of the target object.

Validating Object Instances

The code-behind file for the example application's Default.aspx page starts by importing the namespaces containing the classes the code uses. You can the Validation Application Block assemblies here, and the example target object. The application also uses a Web Service, as you will see shortly, and imports this namespace as well:

using System;

using System.Web.UI;

using System.Text;

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet;

using EntLibSamples;  // defines the sample CompanyDetails class

using SampleService;  // returns valid and invalid CompanyDetails instances

 

The handler for the Create a company using these values... button starts by calling a simple routine that creates an instance of the example target object and sets the properties usinig the values in the text boxes in the page:  

private void CreateLocalCompanyObject()

{

  // create sample object instance and set properties

  EntLibSamples.CompanyDetails companyObject

      = new EntLibSamples.CompanyDetails();

  companyObject.CompanyName = txtName.Text;

  companyObject.CompanyAddress = txtAddress.Text;

  companyObject.CompanyCity = txtCity.Text;

  companyObject.CompanyPostalCode = txtPostalCode.Text;

  companyObject.EmployeeCount = Int32.Parse(txtEmployees.Text);

  companyObject.LastReportDate = DateTime.Parse(txtReportDate.Text);

 

  // display and validate property values

  DisplayAndValidateSampleObject(companyObject);

}

 

After populating the object, the code above calls another routine named DisplayAndValidateSampleObject that begins by creating a StringBuilder containing the property values for display in the page:

private void DisplayAndValidateSampleObject(

                    EntLibSamples.CompanyDetails targetObject)

{

  // read properties for display in the page

  StringBuilder builder

      = new StringBuilder("<b>New Object Properties</b>:<br />");

  builder.Append(String.Format("- Name: <b>{0}</b><br />",

                               targetObject.CompanyName));

  builder.Append(String.Format("- Address: <b>{0}</b><br />",

                               targetObject.CompanyAddress));

  builder.Append(String.Format("- City: <b>{0}</b><br />",

                               targetObject.CompanyCity));

  builder.Append(String.Format("- Postal Code: <b>{0}</b><br />",

                               targetObject.CompanyPostalCode));

  builder.Append(String.Format("- Employees: <b>{0}</b><br />",

                               targetObject.EmployeeCount.ToString()));

  builder.Append(String.Format("- Last Report: <b>{0}</b><p />",

                               targetObject.LastReportDate.ToString()));

  ...

The Validate Method

Next is the validation process. Unlike the ASP.NET UI validation controls, which react to an event in the ASP.NET page cycle to perform validation, the Validation Application Block validators must be explicitly executed by calling the static Validate method of the block. This method takes as parameters the reference to the target object to validate and the name of the rule set containing the validation rules to apply to the target object:

// in C#:

ValidationResults results;

results = Validation.Validate(targetObject, "RulesetName");

 

' in Visual Basic.NET:

Dim results As ValidationResults

results = Validation.Validate(targetObject, "RulesetName")

 

If you have specified a default rule set for the target object (by setting the DefaultRule property of the target object node in the configuration editor), you can omit the second parameter:

// in C#:

ValidationResults results;

results = Validation.Validate(targetObject);

 

' in Visual Basic.NET:

Dim results As ValidationResults

results = Validation.Validate(targetObject)

 

The Validate method also has a generics-based override that takes the type of the target object. You can use this override if you want to indicate the target class type of an inheriting object type:

// in C#:

ValidationResults results;

results = Validation.Validate<targetObjectType>(targetObject, "Ruleset");

 

' in Visual Basic.NET:

Dim results As ValidationResults

results = Validation.Validate(Of targetObjectType)(targetObject, "Ruleset")

 

Displaying the Validation Results

The Validate method returns an instance of the ValidationResults class, which is a collection containing a ValidationResult instance for each validation failure. The ValidationResult class exposes properties that allow you to obtain the value of the Key (the member name if available), the Message describing the validation error, the value of the validator Tag property, the type name of the Target object, and the name of the Validator. There is also the NestedValidationResults property, which exposes a ValidationResults collection containing the validation errors for any nested validators (when using a composite validator).

The example application calls the Validate method, and then checks if there were any validation errors by examining the IsValid property of the returned ValidationResults collection. If there are errors, the code iterates through the collection adding the values of the Key, Tag, and Target properties of each ValidationResults instance to the StringBuilder. If there are no errors, it adds a suitable message to the StringBuilder instead. Finally, the code displays the contents of the StringBuilder in a Label control on the page:

  ...

  // validate the property values using the configured rule set

  ValidationResults results;

  results = Validation.Validate<EntLibSamples.CompanyDetails>(

                                targetObject, "ExampleRuleSet");

 

  // get validation results

  if (!results.IsValid)

  {

    builder.Append("<b>Validation Errors:</b>:<br />");

    foreach (ValidationResult result in results)

    {

      builder.Append(String.Format("- <b>{0}</b><br />", result.Message));

      builder.Append(String.Format("&nbsp; (Key: {0}, ",

                                   result.Key.ToString()));

      builder.Append(String.Format("Tag: {0}, ", result.Tag));

      builder.Append(String.Format("Target: {0})<br />",

                                   result.Target.ToString()));

    }

  }

  else

  {

    builder.Append("All object property values are valid.");

  }

 

  // display results in Label control

  lblResult.Text = builder.ToString();

}

Validating Objects from Other Sources

To demonstrate how useful the Validation Application Block is, and how you can use a rule set to validate object instances wherever they originate from, the example application contains a simple Web Service that returns populated instances of a class compatible with the CompanyDetails target class.

The Example Web Service

The Web Service project, named SampleWebService, uses the following code to expose two Web Methods. The GetValidCompanyInstance method returns an object with valid property values, and the GetInvalidCompanyInstance method returns an instance with invalid values for all of the properties:

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using EntLibSamples;

 

[WebService(Namespace = "http://www.daveandal.net/articlesamples/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class CustomerService : System.Web.Services.WebService

{

 

  [WebMethod]

  public EntLibSamples.CompanyDetails GetValidCompanyInstance()

  {

    // create sample object instance and set properties

    EntLibSamples.CompanyDetails companyObject

        = new EntLibSamples.CompanyDetails();

    companyObject.CompanyName = "FooBar Trading Company";

    companyObject.CompanyAddress = "123, The Industrial Estate";

    companyObject.CompanyCity = "Manchester";

    companyObject.CompanyPostalCode = "12345-1234";

    companyObject.EmployeeCount = 12;

    companyObject.LastReportDate = new DateTime(2007, 03, 03);

    return companyObject;

  }

 

  [WebMethod]

  public EntLibSamples.CompanyDetails GetInvalidCompanyInstance()

  {

    // create sample object instance and set properties

    EntLibSamples.CompanyDetails companyObject

        = new EntLibSamples.CompanyDetails();

    companyObject.CompanyName = "Foo";

    companyObject.CompanyAddress = "Bar";

    companyObject.CompanyCity = "A really long city name that "

                              + "exceeds the validation limit";

    companyObject.CompanyPostalCode = "England";

    companyObject.EmployeeCount = 0;

    companyObject.LastReportDate = new DateTime(2002, 10, 10);

    return companyObject;

  }

}

 

You can see that the Web Service references the EntLibSamples namespace, and creates instances of the example CompanyDetails class from that namespace. However, as you will see shortly, you still need to convert the object exposed by the Web Service to the correct type for validation.  

Validating Objects from the Example Web Service

The code-behind file for the Default.aspx page in the main Web site contains code to access the example Web Service to obtain instances of the target class that it can validate and display. However, although the Web Service returns an object compatible with the CompanyDetails class defined in the configuration, it is not directly convertible. Therefore, the code contains a simple routine that creates a new instance of the local EntLibSamples.CompanyDetails class, and then copies to it the property values from the SampleService.CompanyDetails instance returned by the Web Service:

private EntLibSamples.CompanyDetails ConvertServiceObject(

                      SampleService.CompanyDetails serviceObject)

{

  // generate local CompanyDetails object from the values

  EntLibSamples.CompanyDetails companyObject

      = new EntLibSamples.CompanyDetails();

  companyObject.CompanyName = serviceObject.CompanyName;

  companyObject.CompanyAddress = serviceObject.CompanyAddress;

  companyObject.CompanyCity = serviceObject.CompanyCity;

  companyObject.CompanyPostalCode = serviceObject.CompanyPostalCode;

  companyObject.EmployeeCount = serviceObject.EmployeeCount;

  companyObject.LastReportDate = serviceObject.LastReportDate;

  return companyObject;

}

 

The handlers for the Create a Valid Company using a Web Service and Create an Invalid Company using a Web Service buttons start by creating a reference to the Web Service, and then call the relevant method to get the new object instance. Then they can convert the object to the relevant type using the routine just described, and pass it to the DisplayAndValidateSampleObject method (described earlier) for validation and display. For example, this is the code in the Create a Valid Company... button handler:

// get valid sample object instance from Web Service

CustomerService service = new CustomerService();

SampleService.CompanyDetails serviceObject

    = service.GetValidCompanyInstance();

 

// generate local CompanyDetails object from the values

EntLibSamples.CompanyDetails companyObject

    = ConvertServiceObject(serviceObject);

 

// display and validate property values

DisplayAndValidateSampleObject(companyObject);

 

Figures 6 and 7 show the results when you click the Create a Valid Company using a Web Service and Create an Invalid Company using a Web Service buttons in the example application.

Figure 6The result of validating an object obtained from a remote Web Service with valid property values when you click the "Create a Valid Company using a Web Service" button

Figure 7The result of validating an object obtained from a remote Web Service with invalid property values when you click the "Create an Invalid Company using a Web Service" button

UI Validation Integration in ASP.NET

The Validation Application Block contains UI validation integration features for both Windows Forms and ASP.NET applications. Of course, both of these environments already include built-in UI validation controls and features; however the capability for integrating validation across both the UI and object instances within an application is extremely useful. For example, as you will see in the example application, you can use a common rule set for validation of both UI and objects.

The example application contains a drop-down list where you can turn on and off UI validation for controls in the page. If you set this option to enabled, and then create and validate an object instance, you will see that the page displays the error messages next to each text box, and does not actually create a new object for validation (see Figure 8). Instead, it displays a message indicating that validation errors occurred.

Figure 8The result of validating the proposed values for the properties of the sample object when ASP.NET integration is enabled

The PropertyProxyValidator Control

ASP.NET integration uses a class named PropertyProxyValidator, which implements a control that you can use within an ASP.NET Web page to perform UI validation. This control inherits from the ASP.NET validation control base class named BaseValidator, and is therefore effectively an ASP.NET validation control.

The BaseValidator class exposes properties such as ControlToValidate, Display (None, Static, Dynamic), EnableClientScript, Enabled, IsValid, SetFocusOnError, and ValidationGroup. However, many of these are set within the PropertyProxyValidator class, although – as you will see – you can also set them yourself in code, or with attributes within the control declaration on an .aspx page.

The PropertyProxyValidator class also exposes the Validate method, which you can use to initiate validation of specific validators if required. However, all the instances of the PropertyProxyValidator class you place in a page integrate with the ASP.NET validation system, and so you can cause validation by calling the Validate method of the Page class, and check the result using the IsValid property of the Page class.

 

To use the PropertyProxyValidator class, you simply add instances to the ASP.NET page, either by declaring them within the .aspx file or by generating instances dynamically at runtime and adding them to the Controls collection of the Page object or another container control. The process is identical to adding ASP.NET built-in validation controls such as the RequiredFieldValidator or any other ASP.NET control) to a page.

The only real differences when working with the Validation Application Block compared to the ASP.NET validation controls are:

<%@ Register Assembly="Microsoft.Practices.EnterpriseLibrary

                      .Validation.Integration.AspNet"

             Namespace="Microsoft.Practices.EnterpriseLibrary

                       .Validation.Integration.AspNet"

             TagPrefix="EntLibValidators" %> 

 

<EntLibValidators:PropertyProxyValidator ID="CompanyNameValidator"

     runat="server" ControlToValidate="txtName"

     PropertyName="CompanyName" RulesetName="ExampleRuleSet"

     SourceTypeName="EntLibSamples.CompanyDetails" />

 

Figure 9The Default.aspx page of the example application in Design view showing the PropertyProxyValidator controls

Implementing UI Validation in the Example Application

The first step in adding Validation Block integration with ASP.NET is to declare the PropertyProxyValidator controls for each UI input control. This is simply a matter of dragging the control from the Toolbox (if you have installed it there) onto the page in Design view, or typing and then pasting and copying the declaration in Source view. Also remember that you must add the appropriate @Register directive to the page as well, as described in the previous section of this article.

For each validated UI input control, specify that input control's ID property as the ControlToValidate property of the PropertyProxyValidator control. Also set the RulesetName, SourceTypeName, and PropertyName properties to the appropriate values based on your application configuration. You can view the Default.aspx page in the example application to see the final result.

Validating the UI Control Values

To validate the UI control values, add code to the handler for the button or other control that submits the page. The example application checks the Page.IsValid property, and – if it True – creates an instance of the target object and displays its property values in the page. A separate routine named CreateLocalCompanyObject performs the task of applying the validated UI values to a new instance of the target object, and displaying its properties in the page:

// force validators to check control values

Page.Validate();

if (Page.IsValid)

{

  // create sample object instance and set properties

  CreateLocalCompanyObject();

}

else

{

  lblResult.Text = "Validation errors encountered by ASP.NET "

                 + "Integration Validators<p />";

}

 

You saw the CreateLocalCompanyObject routine used (and described) in the earlier section of this article "Validating Object Instances". As well as creating the new object instance and displaying the property values, this routine performs object-level validation by calling the static Validate method of the Validation Application Block.

Accessing PropertyProxyValidator Controls in Code

One other features of the example application is the ability (as you have seen) to enable and disable UI integrated validation. The code to achieve this demonstrates a useful technique that you can take advantage of to change the behaviour of some or all instances of the PropertyProxyValidator control in your pages.

The Default.aspx page contains a drop-down list that defines two values: "disabled" (value = False) and "enabled" (value = True):

<asp:DropDownList runat="server" ID="lstEnableIntegration">

  <asp:ListItem Text="disabled" Value="false" />

  <asp:ListItem Text="enabled"  Value="true" />

</asp:DropDownList>

 

The example application also contains code in the handler that executes in response to the Page.Load event. This code iterates through all the instances of PropertyProxyValidator controls on the page, setting the Enabled property to that specified in the drop-down list control. Notice that it accesses each validation control using the IValidator interface (from the System.Web.UI namespace), which means that the code will work in a page that contains built-in ASP.NET validation controls as well as PropertyProxyValidator controls:

protected void Page_Load(Object sender, System.EventArgs e)

{

  // set the Enabled property for every EntLib Validator control

  foreach (IValidator validatorControl in Page.GetValidators(null))

  {

    if (validatorControl is PropertyProxyValidator)

    {

      PropertyProxyValidator ctrl

          = (validatorControl as PropertyProxyValidator);

      ctrl.Enabled = Boolean.Parse(lstEnableIntegration.SelectedValue);

    }

  }

}

 

 

The code checks if each validator it finds is of type PropertyProxyValidator, and – if it is – casts the reference to the PropertyProxyValidator type so that it can set the Enabled property to the value selected in the drop-down list. You can use this technique to set the properties of any type of validation control.

The Visual Basic.NET equivalent of the Page.Load routine, showing the different syntax for converting the validator control reference, is:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

  ' set the Enabled property for every EntLib Validator control

  For Each validatorControl As IValidator In Page.GetValidators(Nothing)

    If TypeOf validatorControl Is PropertyProxyValidator Then

      CType(validatorControl, PropertyProxyValidator).Enabled _

            = Boolean.Parse(lstEnableIntegration.SelectedValue)

    End If

  Next

End Sub

 

One final twist to the code in the example application is that, when UI validation integration is enabled, it only creates the target object instance and performs server-side validation of the property values if the UI validation does not detect any validation errors. The actual code used in the example application is:

// check if user has turned on ASP.NET client-side integration

if (lstEnableIntegration.SelectedValue == "true")

{

  // force validators to check control values

  Page.Validate();

  if (Page.IsValid)

  {

    // create sample object instance and set properties

    CreateLocalCompanyObject();

  }

  else

  {

    lblResult.Text = "Validation errors encountered by ASP.NET "

                   + "Integration Validators<p />";

  }

}

else

{

  CreateLocalCompanyObject();

}

Summary

This article discussed how you can take advantage of the Enterprise Library Validation Application Block in ASP.NET applications, concentrating on the use of rule sets that allow validation across the UI and object instances within the application tiers (and, if required, in Windows Forms applications as well).

While ASP.NET provides a fully-featured set of UI validation controls, these do not always fulfil the requirements of enterprise-level applications. The Validation Application Block supports a wider range of validators, has features to allow composition and negation of validators, and supports validation using configuration rules as well as attributes applied directly to classes and class members.

In the example application that accompanies this article, you can see how easy it is to use the Validation Application Block and a rule set to validate local objects, object instances generated from calls to a remote Web Service, and UI input control values.

You can also combine the Validation Application Block validators with the ASP.NET built-in validators if required. The PropertyProxyValidator control that supports ASP.NET integration is itself a descendant of the ASP.NET validator base class, and so behaves and can be handled in the same way as the ASP.NET validation controls.

Having see the capabilities it provides, you may wish to consider using the Validation Application Block to extend the validation capabilities of your code as you build applications that are ever more complex, and more highly distributed in nature.

 

©2007 Alex Homer, Stonebroom Limited, http://www.stonebroom.com