AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1223&pId=-1
Using the Enterprise Library 3 Validation Block in ASP.NET
page
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 27375/ 119

Introduction

With the release of Enterprise Library 3, a brand new Validation Block (Microsoft.Practices.EnterpriseLibrary.Validation) has emerged that allows developers to perform custom validation in an application based on custom validation setup for a business object. When the validation occurs, any validation errors are returned through a ValidationResult collection, so you can get a listing of all the problems that occurred with the validation of a business object.  However, with this new block comes integrated ASP.NET features. Custom validators (like the existing validation controls) can be used to perform the actual validation of the business object and the errors render in the ValidationSummary control. We will see how that works in the rest of the article.

Enterprise Library has several built-in validators that perform a certain validation of data. For instance, it has a StringLengthValidator object that validates that the length of a string falls within a certain range, or a DateTimeRangeValidator for validating that a date occurs within a specific range. You can instantiate these validators and perform validation or each validator has an attribute class associated with it so the validators can be defined as attributes to a property in a business object. This is how the ASP.NET integration can utilize the validation as we will see later. An alternative to this is that the configuration file can setup these validations, but I am going to use the attribute approach as I think it is cleaner and more understandable. Lastly, you can build your own custom validators, which is out of the scope of this article, but I hope to write about it later.

To integrate the business object validation into ASP.NET, the integration library contains a ParameterProxyValidator control that works like any other validator control in the ASP.NET framework. The validator has extra properties that map the validator to the business object property that you want to validate, assuming that the business object property maps directly to an ASP.NET control. Let us look at an example.

Domain Class Validation

The following is a user business component that contains the typical user information. This class has the added validation configured as attributes within the class.

Listing 1

public class User
{
  private string _email = string.Empty;
  private string _name = string.Empty;
  private string _phone = string.Empty;
 
  [StringLengthValidator(7, RangeBoundaryType.Inclusive, 150,
    RangeBoundaryType.Inclusive,
    "Email address must be from 7 and 150 characters", Ruleset = "primary"),
    ContainsCharactersValidator("@.", ContainsCharacters.All,
    "Email must have at an @ and at least one decimal", Ruleset = "primary")]
  public string Email
  {
    get
    {
      return _email;
    }
    set
    {
      _email = value;
    }
  }
 
  [StringLengthValidator(3, RangeBoundaryType.Inclusive, 150,
    RangeBoundaryType.Inclusive,
    "Name must be between 3 and 150 characters long", Ruleset = "primary"),
    ContainsCharactersValidator(" ", ContainsCharacters.All,
    "Name must have at least a space between the names", Ruleset = "primary")]
  public string Name
  {
    get
    {
      return _name;
    }
    set
    {
      _name = value;
    }
  }
 
  [StringLengthValidator(7, RangeBoundaryType.Inclusive, 10,
    RangeBoundaryType.Inclusive,
    "Phone number must be between 7 and 10 characters", Ruleset = "primary"),
    RegexValidator(@"(\d{3})?\d{7}",
    "Phone number is not valid; it can be numbers only", Ruleset = "primary")]
  public string Phone
  {
    get
    {
      return _phone;
    }
    set
    {
      _phone = value;
    }
  }
}

As you can see, several of the validator attributes are defined on the properties of the class.  These exist in the Microsoft.Practices.EnterpriseLibrary.Validation.Validators namespace and are used to validate the data entered.  Of the validators above, here are the ones used and an explanation of what they do:

• StringLengthValidator - This validator ensures the strings are within the defined length.
• ContainsCharactersValidator - This validator ensures that the data for the property has the characters defined in the string.  It could be one of or all of the characters, as defined by the ContainsCharacters enumeration.
• RegexValidator - This validator uses a regex expression to perform the validation.

Each validator attribute has several constructor overloads, allowing you to specify a combination of configuration options for each validator.  Notice that each one has a place where you can enter a message template, allowing you to specify a detailed error message for the problem.  This is used to specify the detailed error messages in the ASP.NET validation scheme as we will see soon.  Note also that a Ruleset property is defined.  The validation works with varying rulesets so that you can change between the rulesets if so desired.  It is an optional property, but can be set using the "Ruleset=" notation in C# or "Ruleset:=" notation in VB.NET.

ASP.NET Validation

So how does this validation work with an ASP.NET page?  In the Quick Starts folder that is installed with Enterprise Library 3, an ASP.NET integration component residing there contains a PropertyProxyValidator.  The validator requires the name of the business object type to validate the name of the property that contains the specific validation details and the Ruleset to enforce.  Using this, it can apply the validators against the data entered and specify a detailed error message.  In the example below a form has been setup to use the business object validators, rather than the ASP.NET default validators, to validate against a the business object defined above.

Listing 2

<table border="0">
<tr>
      <td>Name</td>
      <td>
            <asp:TextBox ID="txtName" runat="server" />
            <el:PropertyProxyValidator ID="ppvName" 
             runat="server" 
             SourceTypeName="Mains.Examples.User,App_Code"
             PropertyName="Name" RulesetName="primary"
           ControlToValidate="txtName">
          *</el:PropertyProxyValidator>
      </td>
</tr>
<tr>
      <td>Phone</td>
      <td>
            <asp:TextBox ID="txtPhone" runat="server" />
            <el:PropertyProxyValidator ID="ppvPhone" 
             runat="server" 
             SourceTypeName="Mains.Examples.User,App_Code"
             PropertyName="Phone" RulesetName="primary" 
           ControlToValidate="txtPhone">
          *</el:PropertyProxyValidator>
      </td>
</tr>
<tr>
      <td>Email</td>
      <td>
            <asp:TextBox ID="txtEmail" runat="server" />
            <el:PropertyProxyValidator ID="ppvEmail"
           runat="server" 
           SourceTypeName="Mains.Examples.User,App_Code"
             PropertyName="Email" RulesetName="primary"  
           ControlToValidate="txtEmail">
          *</el:PropertyProxyValidator>
      </td>
</tr>
<tr>
      <td colspan="2">
            <asp:LinkButton ID="lnkSave" runat="server" 
           OnClick="lnkSave_Click">Save</asp:LinkButton>
      </td>
</tr>
</table>

In the code-behind page I ensure that the page is valid before creating the user in the form.  This could then refresh a GridView control or some other mechanism that displays the users.  The following result to save the user is shown below.

Listing 3

public void lnkSave_Click(object sender, EventArgs e)
{
  if (Page.IsValid)
  {
    User user = new User();
    user.Name = this.txtName.Text;
    user.Phone = this.txtPhone.Text;
    user.Email = this.txtEmail.Text;
    //You could add this user to a repository
    UsersRepository.Add(user);
    Response.Write("<strong>User added</strong>");
  }
}

Upon the page not being valid, the error warnings are shown in the screen.  They are shown below:

·         The name must have at least a space between the names.
The name must be between 3 and 150 characters long.

·         The phone number must be between 7 and 10 characters long.
The phone number is not a valid phone number; it can be numbers only.

·         The email address must be between 7 and 150 characters long.
The email must have at least an @ and at least one decimal.

Conclusion

So, you can see how this can be very beneficial for evaluation purposes.  The proxy validator can be used to work with a business object, which allows you to define all of your validation criteria in that object, instead of defining many different kinds of validators in the ASP.NET page.

Note: This is built on the most recent Community Technology Preview (CTP) release made by Microsoft and although it should be very similar to the final release, it may vary slightly in the final code base.


Product Spotlight
Product Spotlight 

©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-05-26 5:21:59 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search