Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Generic TextBox UserControl With Validation

4.45/5 (7 votes)
29 Sep 2013CPOL2 min read 29.6K   341  
Simple technique to handle text input and validations in single control

Introduction   

Since I am working in ASP.NET, I felt that the use of the validation controls with text box is so easy and good but lots of mark up is involved for this part. So I made a user control in which Required Field Validation and Regular Expression Validation controls both attached with the text box and any developer can use this in his project comfortably.

Background

The idea behind this control is to make a clean mark up of aspx page and handle the things related to text box and validation control with custom properties. Such things make this user control more effective.

Using the Code

The integration is quite simple. Just add a user control (*.ascx) file in to your solution. In my case, I added a user-control file and named it ValidTextBox. The mark up and code behind file are as given below:

ValidTextBox.ascx

ASP.NET
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ValidTextBox.ascx.cs" 
Inherits="Controls_ValidTextBox" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFV" runat="server" ErrorMessage="" 
ControlToValidate="TextBox1" Enabled="false"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="REV" runat="server" ErrorMessage="" 
ControlToValidate="TextBox1" Enabled="false"></asp:RegularExpressionValidator>

ValidTextBox.ascx.cs

C#
using System;
using System.Web.UI.WebControls;
 
public partial class Controls_ValidTextBox : System.Web.UI.UserControl
{
    /// <summary>
    /// Custom properties that can be used against the text box control 
    /// </summary>
    #region "TextBox Custom Properties"
 
    public string Text
    {
        get { return TextBox1.Text; }
        set { TextBox1.Text = value; }
    }
 
    public bool ReadOnly
    {
        set { TextBox1.ReadOnly = value; }
    }
 
    public string CssClass
    {
        set { TextBox1.CssClass = value; }
    }
 
    public TextBoxMode TextMode
    {
        set { TextBox1.TextMode = value; }
    }
 
    public Unit Width
    {
        set { TextBox1.Width = value; }
    }
 
    public Int32 MaxLength
    {
        set { TextBox1.MaxLength = value; }
    }
 
    public int Rows
    {
        set
        {
            if (TextBox1.TextMode == TextBoxMode.MultiLine)
                TextBox1.Rows = value;
        }
    }
 
    public int Columns
    {
        set
        {
            if (TextBox1.TextMode == TextBoxMode.MultiLine)
                TextBox1.Columns = value;
        }
    }
 
    #endregion
 
    /// <summary>
    /// Custom properties that can be used against the validation controls
    /// </summary>
    #region "Validation Controls Custom Properties"
 
    public string RequiredFieldText
    {
        set { RFV.Text = value; }
    }
 
    public string RegularExpressionText
    {
        set { REV.Text = value; }
    }
 
    public ValidatorDisplay RequiredFieldDisplay
    {
        set { RFV.Display = value; }
    }
 
    public ValidatorDisplay RegularExpressionDisplay
    {
        set { REV.Display = value; }
    }
 
    public bool EnabledRequiredField
    {
        set { RFV.Enabled = value; }
    }
 
    public bool EnabledRegularExpression
    {
        set { REV.Enabled = value; }
    }
 
    public string ErrorMsgForRequiredField
    {
        set { RFV.ErrorMessage = value; }
    }
 
    public string ErrorMsgForRegularExpression
    {
        set { REV.ErrorMessage = value; }
    }
 
    public string ValidationExpression
    {
        set { REV.ValidationExpression = value; }
    }
 
    public string ValidationGroup
    {
        set
        {
            REV.ValidationGroup = value;
            RFV.ValidationGroup = value;
        }
    }
 
    #endregion
} 

In the above control, I have defined some custom properties which will be used to operate the control on page. The details are below:

Text Box Related Properties

  • Text: Get or Set the text value of control
  • ReadOnly: Make the textbox readonly
  • CssClass: Define the class for control
  • TextMode: Define the mode, i.e., SingleLine(default), Multiline and Password
  • Width: Set the width of control
  • MaxLength: Set max length of text
  • Rows: Define rows in textbox (applicable only in MultiLine Mode)
  • Columns: Define columns in textbox (applicable only in MultiLine Mode)

Validation Controls Related Properties

  • RequiredFieldText: Set text for Required field control
  • RegularExpressionText: Set text for Regular expression control
  • RequiredFieldDisplay: Set Display mode for Required field control i.e. (None, Static, Dynamic)
  • RegularExpressionDisplay: Set Display mode for Regular expression control i.e. (None, Static, Dynamic)
  • EnabledRequiredField: Enable/Disable Required Control
  • EnabledRegularExpression: Enable/Disable RegularExpression Control
  • ErrorMsgForRequiredField: Set error message for Required Control
  • ErrorMsgForRegularExpression: Set error message for RegularExpression Control
  • ValidationExpression: Set the validation expression for RegularExpression Control
  • ValidationGroup: Set the validation group of both validation controls

Now you can use this control in your page and use its properties to modify its behavior on page. The new custom properties according to the developer requirement can also be defined.

How to Use the Above Control

To use this control is so simple as developers use usercontrols in many ways like Registered it on page or in web.config globally or dynamically as well. So, I am using the first approach because it's good for beginner developers to understand. I added this control on my Default.aspx page via dragging it on page and prepared a form with the help of it. The mark up would be:

Default.aspx

HTML
<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<%@ Register Src="Controls/ValidTextBox.ascx" 
TagName="ValidTextBox" TagPrefix="uc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1 { width: 100%; }
        .style2 { width: 180px; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td class="style2">Name</td>
                <td>
                    <uc:ValidTextBox ID="ValidTextBox1" 
                    runat="server" EnabledRequiredField="True" 
                        ErrorMsgForRequiredField="*required" 
                        RequiredFieldDisplay="Dynamic" 
                        ValidationGroup="submit" Width="300" />
                </td>
            </tr>
            <tr>
                <td class="style2">Address</td>
                <td>
                    <uc:ValidTextBox ID="ValidTextBox2" 
                    runat="server" EnabledRequiredField="True" 
                        ErrorMsgForRequiredField="*required" 
                        RegularExpressionDisplay="Dynamic" 
                        Rows="5" TextMode="MultiLine" 
                        ValidationGroup="submit" Width="300" />
                </td>
            </tr>
            <tr>
                <td class="style2">Email</td>
                <td>
                    <uc:ValidTextBox ID="ValidTextBox3" runat="server" 
                        EnabledRegularExpression="True" 
                        EnabledRequiredField="True" 
                        ErrorMsgForRegularExpression="*Invalid" 
                        ErrorMsgForRequiredField="*required" 
                        RegularExpressionDisplay="Dynamic" 
                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
                        ValidationGroup="submit" Width="300" />
                </td>
            </tr>
            <tr>
                <td class="style2">Password</td>
                <td>
                    <uc:ValidTextBox ID="ValidTextBox4" 
                    runat="server" EnabledRequiredField="True" 
                        ErrorMsgForRequiredField="*required" 
                        RegularExpressionDisplay="Dynamic" 
                        TextMode="Password" 
                        ValidationGroup="submit" Width="300" />
                </td>
            </tr>
            <tr>
                <td class="style2">&nbsp;</td>
                <td>
                    <asp:Button ID="btnSubmit" 
                    runat="server" OnClick="btnSubmit_Click" 
                        Text="Submit" ValidationGroup="submit" />
                    &nbsp;<asp:Button ID="btnReset" 
                    runat="server" Text="Reset" 
                        onclick="btnReset_Click" />
                </td>
            </tr>
        </table>
        <asp:Literal ID="ltMessage" runat="server"></asp:Literal>
        <br />
    </div>
    </form>
</body>
</html>

Default.aspx.cs

C#
using System;
 
public partial class _Default : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ltMessage.Text = "Form has been validated";
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        ValidTextBox1.Text = "";
        ValidTextBox2.Text = "";
        ValidTextBox3.Text = "";
        ValidTextBox4.Text = "";
        ltMessage.Text = "";
    }
}

Conclusion

This is all about the Generic TextBox Validation Control. I hope this will help you in your applications and make your efforts less while using TextBox with validations. Other developers can add more properties in user control according to their requirement. It's just a way to make things easier during development.

Thanks for reading. Smile | :)

License

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