XML Driven Validation


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 a 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.cs)

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Collections.Specialized;

using 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 sealed class Validation

    {

        private static Validation validationInstance = 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 HybridDictionary cachedValidationFields = new HybridDictionary();

 

        public static Validation Instance

        {

            get { return validationInstance; }

        }

 

        public static ValidationField Field(string fieldName)

        {

            return ((ValidationField)(validationInstance.cachedValidationFields[fieldName]));

        }

 

        /// <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 String Name = 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 int MaxLength = 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 int MinValue = 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 int MaxValue = 0;

 

            /// <summary>

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

            /// ValidationExpression property of a RegularExpressionValidator.

            /// </summary>

 

            public String RegEx = String.Empty;

 

            /// <summary>

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

            /// </summary>

 

            public String RegExErrorMessage = String.Empty;

 

            /// <summary>

            /// RequiredErrorMessage is the error message to display

            /// if the required field validation fails.

            /// </summary>

 

            public String RequiredErrorMessage = String.Empty;

 

            /// <summary>

            /// RangeErrorMessage is the error message to display

            /// if the range field validation fails.

            /// </summary>

 

            public String RangeErrorMessage = String.Empty;

        }

 

        /// <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 Validation()

        {

            try

            {

                #region Reads ScreenValidations.xml into memory

 

                DataSet ds = new DataSet();

                //DataRow dr;

                string ValidationFilePath = WebConfigurationManager.AppSettings["ScreenValidation"].ToString();

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

 

                #endregion

 

                foreach (DataRow dr in ds.Tables[0].Rows)

                {

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

 

                    ValidationField Field = 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.

 

                    cachedValidationFields.Add(Field.Name, Field);

 

                    #endregion

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

 

        /// <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 static void Reset()

        {

            validationInstance = new Validation();

        }

    }

} 

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 void Page_Load(object sender, System.EventArgs e)

{

    if (!IsPostBack)

    {

        BindValidation();

    }

} 

 

protected void 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;

    }

    catch (Exception ex)

    {

        //throw;

    }

} 

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.  


Similar Articles