ARTICLE

XML Driven Validation

Posted by Subal Mishra Articles | Visual Basic 2010 July 25, 2007
This article/tutorial tells us to develop a generic XML based Validation engine to be used in any Web application.
 
Reader Level:

Importance of Validation

Input validation ensures a user not only enters or selects values when required but also enters appropriate and correctly formatted values. Any user input form/window that support insert, update, delete or any calculated functions are all common scenarios where input validation should be implemented.

It's important to ensure that data you store in a database is standardized, comprehensive and complete. Invalid phone numbers, incorrectly formatted email addresses or empty addresses amongst other things will undermine the effectiveness and quality of the data in your web application.

One should also be aware of script errors that might be caused by an application user entering incorrect variable types e.g. a user entering an alphanumeric value in an amount calculation box when an integer is required. Input validation also protects against a malicious user attempting to directly enter HTML, JavaScript, SQL or other inappropriate scripts.

The Validation Controls

The ASP.Net provides 6 validation controls including the ValidationSummary control. These are:

  • RequiredFieldValidator 
  • RegularExpressionValidator 
  • RangeValidator
  • CompareValidator
  • CustomValidator
  • ValidationSummary

The ASP.NET validation controls make form validation a lot faster and easier. Because we all know what the properties of these controls and how to use them, I am not going to explain the same.

The Problem Identified

With ASP.Net validation can now be accomplished in a matter of minutes and have the flexibility both in the types of validation and the error message that is displayed to the end user. Where in a small 5-10 page of data entry application, hard coding error messages and regular expression into the validation controls is the easiest and fastest way to develop. 

One will likely wind up with 2 or 3 "Phone Number" textboxes, each having a "Phone" required field validator and regular expression validator, each with their own hard-coded error message. Though not an ideal situation, it is certainly manageable.

But, as the page count increases, however, maintaining these strings becomes a headache, especially when the changes are more frequent in showing error message syntax. When you ask to change "Phone is a required field" to "Please enters Phone number" how many lines of code are touched?

The Solution Identified - An XML Based Validation Approach 

Below are the requirements for the solution of the above-mentioned problem:

  1. Developers should be able to view and edit any validation with minimal effort.
  2. To provide a common way to validate the same kind of input field in different pages in an application. 
  3. The performance must be fast. These values could be accessed from every page in the application.

To implement the above I have used the following:

  1. An XML file to store the input field key, max length, min length, error messages and regular expression.
  2. A C# class in a singleton approach that stores the XML data in cached manner and certain methods to make use of this XML based validation engine in ASP.NET pages/forms. 

The XML File (ScreenValidations.xml) 

<?xml version="1.0" encoding="utf-8" ?>

<!-- This XML provides the elements to define the input data validations for various screens of this web application. -->

<Validations>

  <Field>

    <Name>PolicyNumber</Name>

    <MaxLength>7</MaxLength>

    <MinValue>0</MinValue>

    <MaxValue>0</MaxValue>

    <RegEx>^[a-zA-Z]{0,50}$</RegEx>

    <RegExErrorMessage>Invalid Policy Number</RegExErrorMessage>

    <RequiredErrorMessage>Please enter the Policy Number

    </RequiredErrorMessage>

    <RangeErrorMessage>Invalid PolicyNumber</RangeErrorMessage>

  </Field>

  <Field>

    <Name>Date</Name>

    <MaxLength>10</MaxLength>

    <MinValue>0</MinValue>

    <MaxValue>0</MaxValue>

    <RegEx>^\d{1,2}\/\d{1,2}\/\d{4}$</RegEx>

    <RegExErrorMessage> Invalid Date. Date must be in MMDDYYYY format

    </RegExErrorMessage>

    <RequiredErrorMessage>Date must be in MMDDYYYY format

    </RequiredErrorMessage>

    <RangeErrorMessage></RangeErrorMessage>

  </Field>

  <Field>

    <Name>Price</Name>

    <MaxLength>13</MaxLength>

    <MinValue>0</MinValue>

    <MaxValue>0</MaxValue>

    <RegEx>

   (?n:(^\$?(?!0,?\d)\d{1,3}(?=(?&lt;1&gt;,)|(?&lt;1&gt;))(\k&lt;1&gt;\d{3})*(\.\d\d)?)$)

   </RegEx>

    <RegExErrorMessage>

        Invalid Premium amount. Digits to the left of the decimal point can optionally be formatted with commas, in standard US currency format. If the decimal point is present, it must be followed by exactly two digits to the right. Matches an optional preceding dollar sign.

     </RegExErrorMessage>

     <RequiredErrorMessage>Please enter the Premium Amount  

     </RequiredErrorMessage>

     <RangeErrorMessage>Invalid Premium </RangeErrorMessage>

  </Field>

</Validations> 

The Elements of the above XML File 

  • <Field> defines a field and its child elements that would be used in the calling code for validation.
  • <Name> is the unique key used in the calling code to access the validation expression and other values.
  • <MaxLength> is the maxlength property of the control.
  • <MinValue> & <MaxValue> are used for range validations if any.
  • <RegEx> is the regular expression that would be assigned to the validation expression property of a control in your application at runtime.
  • <RegExErrorMessage> is the message to display to the user when the regular expression validation fails.         
  • <RequiredErrorMessage> is the message to display to the user when the required control left empty or unselected.         
  • <RangeErrorMessage> is the message to display to the user when the input value entered is not in the range defined. 

The above XML file can be modified throughout the development process as and when the new fields are being added / removed and/or whenever any changes are requested. 

The Field Validation Class that loads the XML File into memory (Validation.vb)

Imports System

Imports System.Collections.Generic

Imports System.Text

Imports System.Data

Imports System.Collections.Specialized

Imports System.Web.Configuration

 

Namespace Components

    ''' <summary>

    '''This class provides common storage for multiple values based on a key.

    '''Screen input field controls would be the key and the values stored

    '''would be RequiredErrorMessage, RegularExpressionErrorMessage, and RegularExpression.

    '''These values will be accessed on the first page load of nearly every page in the web application.

    '''This Validation process consists of the following:

    '''An XML file used to store the keys and values (ScreenValidations.xml).

    '''A singleton class (Validation) that stores the XML data in memory.

    '''A method named BindValidation() that appears on every page containing a validator or textbox.

    '''The first time a page loads a call is made to BindValidation(),

    '''which retrieves the values from the singleton and assigns them to the

    '''appropriate validator or textbox.

    '''The Validation class is NotInheritable, meaning it cannot be extended through inheritance.

    '''This class is not designed to be a base class and inheriting from it would not

    '''make much sense from an object oriented perspective

    ''' </summary>

 

    Public NotInheritable Class Validation

        Private Shared validationInstance As New Validation()

 

        ''' <summary>

        ''' HybridDictionary cachedValidationFields, populated in Validation's constructor,

        ''' is the core of this class, as it holds the collection of ValidationField objects.

        ''' cachedValidationFields can only be accessed through the Field property,

        ''' which retrieves a particular ValidationField object from the collection

        ''' based on a string key.

        ''' </summary>

 

        Private cachedValidationFields As New HybridDictionary()

 

        Public Shared ReadOnly Property Instance() As Validation

            Get

                Return validationInstance

            End Get

        End Property

 

        Public Shared Function Field(ByVal fieldName As String) As ValidationField

            Return DirectCast((validationInstance.cachedValidationFields(fieldName)), ValidationField)

        End Function

 

        ''' <summary>

        ''' Contains the structure for the ValidationField

        ''' </summary>

 

        Public Class ValidationField

            ''' <summary>

            ''' Name is the key used in the calling code to retrieve the appropriate values.

            ''' </summary>

 

            Public Name As String = [String].Empty

 

            ''' <summary>

            ''' MaxLength is another property that is typically hard-coded

            ''' and duplicated throughout code.

            ''' It corresponds to the MaxLength property of a textbox.

            ''' </summary>

 

            Public MaxLength As Integer = 0

 

            ''' <summary>

            ''' Min Value is another property that is typically hard-coded and

            ''' duplicated throughout code. It corresponds to the min value for a range validator.

            ''' </summary>

 

            Public MinValue As Integer = 0

 

            ''' <summary>

            ''' Max Value is another property that is typically hard-coded and

            ''' duplicated throughout code. It corresponds to the max value for a range validator.

            ''' </summary>

 

            Public MaxValue As Integer = 0

 

            ''' <summary>

            ''' RegEx is the regular expression that would be assigned to the

            ''' ValidationExpression property of a RegularExpressionValidator.

            ''' </summary>

 

            Public RegEx As String = [String].Empty

 

            ''' <summary>

            ''' RegExErrorMessage is the error message to display if the regular expression validation fails.

            ''' </summary>

 

            Public RegExErrorMessage As String = [String].Empty

 

            ''' <summary>

            ''' RequiredErrorMessage is the error message to display

            ''' if the required field validation fails.

            ''' </summary>

 

            Public RequiredErrorMessage As String = [String].Empty

 

            ''' <summary>

            ''' RangeErrorMessage is the error message to display

            ''' if the range field validation fails.

            ''' </summary>

 

            Public RangeErrorMessage As String = [String].Empty

        End Class

 

        ''' <summary>

        '''The constructor is only called once, the first time this class is instantiated.

        '''Every time an instance of this object is called after the first time,

        '''the "in memory" copy contained in validationInstance is used.

        '''The constructor performs the basics.

        '''It reads ScreenValidations.xml into memory, in a DataSet.

        '''It reads through each row of the DataSet and populates a new ValidationField object.

        '''Finally, it adds the ValidationField object to the cachedValidationFields collection.

        '''Once the DataSet is populated it is not changed until it is reloaded from the

        '''XML when the application is restarted.

        ''' </summary>

 

        Private Sub New()

            Try

                    #region Reads ScreenValidations.xml into memory

 

                Dim ds As New DataSet()

                'DataRow dr;

                Dim ValidationFilePath As String = WebConfigurationManager.AppSettings("ScreenValidation").ToString()

                ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath(ValidationFilePath))

 

                    #endregion

 

                For Each dr As DataRow In ds.Tables(0).Rows

                    #region Reads through each row of the DataSet and populates a new Field object

 

                    Dim Field As New ValidationField()

                    Field.Name = dr("Name").ToString()

                    Field.MaxLength = Utilities.Util.ConvertInt(dr("MaxLength"), System.Globalization.NumberStyles.[Integer])

                    Field.MinValue = Utilities.Util.ConvertInt(dr("MinValue"), System.Globalization.NumberStyles.[Integer])

                    Field.MaxValue = Utilities.Util.ConvertInt(dr("MaxValue"), System.Globalization.NumberStyles.[Integer])

                    Field.RegEx = dr("RegEx").ToString()

                    Field.RegExErrorMessage = dr("RegExErrorMessage").ToString()

                    Field.RequiredErrorMessage = dr("RequiredErrorMessage").ToString()

                    Field.RangeErrorMessage = dr("RangeErrorMessage").ToString()

 

                     #endregion

 

                    #region Adds the Field object to the cachedValidationFields collection.

 

 

                    #endregion

                    cachedValidationFields.Add(Field.Name, Field)

                Next

            Catch ex As Exception

                Throw ex

            End Try

        End Sub

 

        ''' <summary>

        ''' The Reset method allows for dynamic reloading of ScreenValidations.xml during runtime.

        ''' Any screen/page/class could very easily call this method in a event handler to

        ''' allow administrators to reload ScreenValidations.xml on the fly without restarting

        ''' the application.

        ''' </summary>

 

        Public Shared Sub Reset()

            validationInstance = New Validation()

        End Sub

    End Class

End Namespace

How to access/implement the Validation in web page: 

Suppose you have already designed your web page and placed the appropriate validation controls.  A method named BindValidation() that appears on every page containing a validator or textbox. The first time a page loads a call is made to BindValidation(),which retrieves the values from the singleton and assigns them to the appropriate validator or textbox.

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

    If Not IsPostBack Then

        BindValidation()

    End If

End Sub

 

Protected Sub BindValidation()

    Try

        txtDate.Validate = True

        txtDate.ErrorMessage = Validation.Field("Date").RequiredErrorMessage

        txtDate.RegularExpression = Validation.Field("Date").RegEx

        txtDate.RegularExpErrorMessage = Validation.Field("Date").RegExErrorMessage

 

        txtPrice.Validate = True

        txtPrice.ErrorMessage = Validation.Field("Price").RequiredErrorMessage

        txtPrice.RegularExpression = Validation.Field("Price").RegEx

        txtPrice.RegularExpErrorMessage = Validation.Field("Price").RegExErrorMessage

        'throw;

    Catch ex As Exception

    End Try

End Sub

Advantage and Disadvantage of this approach:

The main advantage of this approach is the maintainability provided by storing the myriad of string values in a single repository. In addition, using XML means only a text editor is required to modify these values, eliminating the need for recompilation. Finally, this approach allows the web and business tier to easily share the same regular expressions and error messages.  

One disadvantage of this approach is that the ViewState is slightly larger than when hard-coding the values into the validators. When the values are hard-coded they are compiled into the dll, but when they are set dynamically at runtime they must be passed in the ViewState. This should be ok in the applications where performance is not a bigger issue. 

Conclusion:

Maintenance is a nightmare for large applications that comes with many challenges. As the applications grow they tend to contain large quantities of repetitive information. The Validation class offers an easy to maintain, XML-based solution to an otherwise difficult problem.  

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON (http://www.c-sharpcorner.com/). 

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor