TIP: Masked Textbox

Introduction

When working with Web forms, you have to put in validation. Some validations are very common—such as Integer only, string only, web address, email address, SSN number, Date, and so forth. For pages that contain such type of validation, you have to do the repeated task of adding a textbox and then the Required field validator and regular expression validator. If you develop a smart control all validation is done by itself. You can save lot of development time. This inspired me to develop this custom control.

Usage

This control is useful for creating forms that require user data and check that the user has entered valid data. The types of data can be:

  • Integer only
  • String only
  • Email address
  • Date
  • Web Address
  • SSN number
  • US zip code

Background

The basic idea is to put together TextBox, RequiredField validator, and RegularExpressionValidator and hide the complexity from the developer. The developer needs to assign certain properties; the control does all the validation on its own.

Using the Code

Just add the MaskedTextBox.dll in the VS.NET tool bar or add a reference to MaskedTextBox.dll. Assign these properties:

  • DataType (you can select Integer, string,email, web address, date, SSN number, and US zipcode)
  • Display (mode of message display; for example, Dynamic, static, or none)
  • ErrorMessage (message when validation fails)
  • RequiredErrorMessage (message when textbox is empty)
using System;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;
using System.Web.UI.WebControls;

[assembly: TagPrefix ("MaskedTextBox", "Saifi") ]
namespace controlLib
{
   ///<summary>
   /// Created By saifi Hasan
   ///</summary>
   public enum DataTypeEnum { IntegerOnly  =0,
                              StringOnly   =1,
                              EmailAddress =2,
                              WebAddress   =3,
                              SSNNumber    =4,
                              USZipCode    =5,
                              DateMMDDYYY  =6,
                              DateYYYMMDD  =7
                            } ;
   [ToolboxBitmap(typeof(System.Web.UI.WebControls.TextBox)) ,
    ToolboxData("<{0}:MaskedTextBox runat=\"server\"
                Required=\"true\" DataType=\"IntegerOnly\" >
    Designer( "System.Web.UI.Design.WebControls" ,
              typeof(System.Web.UI.WebControls.TextBox))
   ]

   public class MaskedTextBox :
      System.Web.UI.WebControls.WebControl ,INamingContainer

   {
      #region Private Members
         private RegularExpressionValidator  _emailFormatValidator;
         private RequiredFieldValidator      _emailRequiredValidator;
         private TextBox _emailTextBox;
         private DataTypeEnum _DataType ;
         private string _ErrorMessageCssClass;
         private string _ErrorMessage=  string.Empty;
         private string _RequiredErrorMessage = string.Empty;
         private bool   _Required =false;
         private ValidatorDisplay _Display  = ValidatorDisplay.Dynamic;

         string[] arrRegEx = {
            "^([-]|[0-9])[0-9]*$",    //integer Only
            "[^a-zA-Z]",              //string Only
            //Email address
            @"[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}",
            //Internet Email Only
            @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?",
            @"\d{3}-\d{2}-\d{4}",    //SSN No
            @"\d{5}(-\d{4})?",    //US Zip Code
            @"(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])
               [- /.](19|20)\d\d",    //Date in MM-DD-YYY format
            @"(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12]
               [0-9]|3[01])"          //Date in YYY-MM-DD format
         };

      #endregion

      #region Properties
         [Category("Data"),
          DefaultValue(1),
          Description ("Text box DataType") ]
         public DataTypeEnum DataType
         {
            get { return _DataType ;}
            set { _DataType = value;}
         }

         [Category("Data"),
          DefaultValue(1),
          Description ("Display Mode") ]
         public ValidatorDisplay Display
         {
            get { return _Display ;}
            set { _Display = value;}
         }

         [Category("Data"),
          DefaultValue(1),
          Description ("Text box DataType") ]
         public bool Required
         {
            get { return _Required ;}
            set { _Required = value;}
         }

         [Category("Data"),
          DefaultValue(1),
          Description ("Error Message format") ]
         public string ErrorMessage
         {
            get { return _ErrorMessage ;}
            set { _ErrorMessage value  ;}
         }

         [Category("Data"),
          DefaultValue(1),
          Description ("Error Message for Required Validation") ]
         public string RequiredErrorMessage
         {
            get { return _RequiredErrorMessage  ;}
         }

      #endregion

      #region Constructor
      public MaskedTextBox()
      {

      }
      #endregion

      protected override void OnInit(EventArgs e)
      {

         base.OnInit (e);
      }

      protected override void CreateChildControls()
      {

         Controls.Clear();

         _emailTextBox = new TextBox();
         _emailTextBox.ID = "emailTextBox";

         _emailRequiredValidator = new RequiredFieldValidator();
         _emailRequiredValidator.ID = "emailRequiredValidator";
         _emailRequiredValidator.ControlToValidate =
            _emailTextBox.UniqueID;

         _emailRequiredValidator.ErrorMessage = _RequiredErrorMessage;
         _emailRequiredValidator.Display = _Display;


         _emailFormatValidator = new RegularExpressionValidator();
         _emailFormatValidator.ID = "emailFormatValidator";
         _emailFormatValidator.ControlToValidate = _emailTextBox.ID;
         int iValidExp = _DataType.GetHashCode();

         _emailFormatValidator.ValidationExpression =
            arrRegEx[iValidExp];

         _emailFormatValidator.ErrorMessage = _ErrorMessage;
         _emailFormatValidator.Display = _Display;

         this.Controls.Add(_emailTextBox);
         if(_Required)
         {
            this.Controls.Add(_emailRequiredValidator);
         }
         this.Controls.Add(_emailFormatValidator);

         /*end validator*/

      }

      #region Render Method
      protected override void Render(System.Web.UI.HtmlTextWriter writer)
      {

         base.Render (writer);
      }
      #endregion

   }
}


About the Author

saifi hasan

I have been in development Web Application, Web Sevices for last 3 yrs.Currently working with TCS India

Downloads

Comments

  • See it!

    Posted by wherlereeni on 10/22/2012 10:59pm

    Aloha! what does viagra look like , cheapest cialis and fast delivery

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: October 29, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this eSeminar, Gene Kim will discuss these survey findings and will share woeful tales of artifact management gone wrong! Gene will also share examples of how …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds