Integrating the Validation block with ASP.NET

The Validation Application Block provides the PropertyProxyValidator control to validate user input by associating the existing validation rules of a particular type by mapping it to an ASP.NET server control. Apart from the common assembly references and Validation Application Block reference, we have to add the Enterprise Library Validation Application Block ASP.NET Integration assembly to leverage and integrate the Validation Application Block with ASP.NET.

We must include the integration assembly using the @Register directive:

<%@ Register Assembly="Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet"
Namespace="Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet"
TagPrefix="vabaspnet" %>

The PropertyProxyValidator control works like the ASP.NET Validator control but under the hood it acts as a wrapper that uses the existing validation rules. The four basic properties of this control are as follows:

  • ControlToValidate: ID of the input control to validate
  • SourceTypeName: Fully qualified type name whose property will be validated
  • PropertyName : Property to be validated
  • RulesetName : Rule Set to be applied for validation

The ASP.NET syntax to associate the Server control with the PropertyProxyValidator control and the corresponding class and property mapping are shown next:

<asp:TextBox ID="txtFirstName" runat="server" Width="235px"></asp:TextBox>
<vabaspnet:PropertyProxyValidator id="firstNameValidator" runat="server"
ControlToValidate="txtFirstName" PropertyName="FirstName"
RulesetName="Ruleset.Insert" SourceTypeName="VAB_ASPNET_Integration.Author"
OnValueConvert="firstNameValidator_ValueConvert"></vabaspnet:PropertyProxyValidator>

This code will display the error message if the First Name does not satisfy any rules of the FirstName property of the Author class. Also, it exposes a ValueConvert event which can be used to convert the string representation value to the required type. The given code block converts the First Name to null value if the First Name is empty.

protected void firstNameValidator_ValueConvert(object sender, Microsoft.Practices.EnterpriseLibrary.Validation.Integration.ValueConvertEventArgs e)
{
string firstName = e.ValueToConvert as string;
if (firstName == string.Empty) e.ConvertedValue = null;
}

The following screenshot shows the validation result with the error message Invalid Email ID for the Email ID field.

Integrating the Validation block with ASP.NET
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.50.222