Click here to Skip to main content
16,004,887 members
Articles / Programming Languages / C#
Article

Text Box Control with built in Data validation

Rate me:
Please Sign up or sign in to vote.
3.70/5 (4 votes)
30 Oct 2007CPOL2 min read 25.4K   416   8  
An article on creating a composite text box control to perform its validation on data.

Introduction

Textbox is one of the most common and frequently used webcontrol to get input from client. Based on the project's requirement one might be in need of performing different type of validation on the input. Though .Net offers variety of validators to validate, to validate say 10 textboxes we need to have 10 validator controls and then configure the same. Sometimes this might frustrate as we keep on adding similar code and any change in validation will involve lot of code change. When I encountered a similar situation I decided to write a custom control which will perform the necessary validations by itself.

Background

The following items were at back of my mind when I was set to create the control. The Control should be flexible enough to perform different type of validation like required, regex etc. The control should be capable enough to show different type of error messages. When more than one control is used in the same page then we must be able to group the validations performed by using validation group. As business requirement change, we should have a way to extend its default validation/behaviour.

Using the code

I have created a Custom control by creating a class TextControl by extending the composite control and implementing the INamingContainer. Any web app can just include this dll as a reference and then import the controls in the aspx page using the

C#
<%@ Register Assembly="SS.Web.UI.Controls" Namespace="SS.Web.UI.Controls"  TagPrefix="SS"  %>

At the minimum we have a Label, a TextBox, a Requried Field Validator and a Custom Validator. The Required Field Validator and Custom Validator are used to validate the input given through the text control. The label is used to display the caption.

C#
protected Label lblCaption = new Label();
protected TextBox txtInput = new TextBox();
protected CustomValidator cvCustomVal = new CustomValidator();
protected RequiredFieldValidator regVal = new RequiredFieldValidator();

Have exposed certain properties like Text, Caption, RegEx, RegExErrorMessage, ValidationGroup, Required, Validate, RequiredErrorMessage, MaxLength to change its normal behaviour.

Child controls are created and ensured by the overriding CreateChildControls method

C#
#region Child Controls
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        lblCaption.ID = this.ID + "_lblCaption";
        txtInput.ID = this.ID + "_text1";


        regVal.ID = this.ID + "_reqValidator";
        regVal.ControlToValidate = txtInput.ID;
        regVal.EnableClientScript = false;
        regVal.ErrorMessage = RequiredErrorMessage;
        regVal.Text = "!";


        cvCustomVal.ID = this.ID + "_Validator";
        cvCustomVal.ControlToValidate = txtInput.ID;
        cvCustomVal.EnableClientScript = false;
        cvCustomVal.ErrorMessage = RegExErrorMessage;
        cvCustomVal.Text = "!";


        Controls.Add(new LiteralControl("<tr><td>"));
        Controls.Add(lblCaption);
        Controls.Add(new LiteralControl("</td><td>"));
        Controls.Add(txtInput);
        Controls.Add(regVal);
        Controls.Add(cvCustomVal);
        Controls.Add(new LiteralControl("</td></tr>"));
    }
    #endregion

OnInit method takes care of wiring up the validation event to the custom validator

C#
protected override void OnInit(EventArgs e)
{
  // if the reqd validation is not reqd turn off the reqd validator
   if (!Required)
      regVal.Visible = false;
  // set the max length if the user has specified
  if (MaxLength > 0)
      txtInput.MaxLength = MaxLength;
  // assign the validation group.
  if (!string.IsNullOrEmpty(ValidationGroup))
  {
      txtInput.ValidationGroup = ValidationGroup;
      regVal.ValidationGroup = ValidationGroup;
      cvCustomVal.ValidationGroup = ValidationGroup;
  }
  //wire up the event handler.
  cvCustomVal.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(this.validator_ServerValidate);

  base.OnInit(e);
}

The following code shows the validation section of the control. By default if the validation is turned on then it performs regex validation(Alpha numerals). The user can also change the regex. If the application has initialized the event "ValidateEvent" in the code-behind class, then just raise the event or perform the predefined validation. This feature will be of great help for writing any specific business validation. The attached source has examples for writing the specific business validation.

C#
#region validation Event

     protected void validator_ServerValidate(object source, ServerValidateEventArgs args)
     {
         if (ValidateEvent != null)
         {
             OnValidateEvent(args);
         }
         else
         {
             Regex reg = null;

             if (string.IsNullOrEmpty(RegEx))
                 reg = new Regex("^[A-Za-z0-9 ]+$");
             else
                 reg = new Regex(RegEx);

             if (Validate && !reg.IsMatch((args.Value)))
             {
                 args.IsValid = false;
                 cvCustomVal.ErrorMessage = RegExErrorMessage;

             }
         }
     }
     #endregion

Conclusion

Usage of this Textcontrol greatly reduces the developers time in writing the validation logic.

History

Intial version - 31 Oct 2007

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Web App Developer, Chennai, India

Comments and Discussions

 
-- There are no messages in this forum --