Click here to Skip to main content
15,897,704 members
Articles / Programming Languages / C#

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.3K   416   8  
An article on creating a composite text box control to perform its validation on data.
/* --------------------------------------------------------------------------------------
 * Module.....:	TextControl
 * Created on.:	10/15/07
 * Created by.:	Balamurugan R A. 
 * Desc.......:	Common Text Control to perform routine validations
 * --------------------------------------------------------------------------------------
 */
using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;



namespace SS.Web.UI.Controls
{
    
    public class TextControl : CompositeControl, INamingContainer
    {
        #region variable declaration

        private string __labelCaption = string.Empty;
        private string __regEx = string.Empty;
        private string __regExErrMsg = "Please enter only Alpha Numerals";

        private bool __reqd = false;
        private int __maxLength;
        private bool __validate = false;
        private string __reqdErrMsg = "This field Cant be Empty";
        private string __validationGroup = string.Empty;
        private string __textValue = string.Empty;

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

        #endregion

        #region custom validation event
        public event CustomValidationHandler ValidateEvent;

        protected virtual void OnValidateEvent(ServerValidateEventArgs args)
        {
            if (ValidateEvent != null)
            {
                ValidateEvent(this, args);
            }
        }
        #endregion

        #region properties

        public string Text
        {
            get
            {
                this.EnsureChildControls();
                TextBox txt = this.FindControl(this.ID + "_text1") as TextBox;
                if (txt != null)
                {
                    return txt.Text;

                }
                else
                    return string.Empty;

            }
            set
            {
                this.EnsureChildControls();
                TextBox txt = this.FindControl(this.ID + "_text1") as TextBox;
                if (txt != null)
                {
                    txt.Text = value;
                    __textValue = value;
                }

            }
        }

        public string Caption
        {
            get
            {
                this.EnsureChildControls();
                return __labelCaption;
            }
            set
            {
                this.EnsureChildControls();
                __labelCaption = value;
            }
        }

        public string RegEx
        {
            get
            {
                this.EnsureChildControls();
                return __regEx;
            }
            set
            {
                this.EnsureChildControls();
                __regEx = value;
            }
        }

        public string RegExErrorMessage
        {
            get
            {
                this.EnsureChildControls();
                return __regExErrMsg;
            }
            set
            {
                this.EnsureChildControls();
                __regExErrMsg = value;
            }
        }

        public string ValidationGroup
        {
            get
            {
                this.EnsureChildControls();
                return __validationGroup;
            }
            set
            {
                this.EnsureChildControls();
                __validationGroup = value;
            }
        }
        
        public bool Required
        {
            get
            {
                this.EnsureChildControls();
                return __reqd;
            }
            set
            {
                this.EnsureChildControls();
                __reqd = value;
            }
        }

        public bool Validate
        {
            get
            {
                this.EnsureChildControls();
                return __validate;
            }
            set
            {
                this.EnsureChildControls();
                __validate = value;
            }
        }

        public int MaxLength
        {
            get
            {
                this.EnsureChildControls();
                return __maxLength;
            }
            set
            {
                this.EnsureChildControls();
                __maxLength = value;
            }
        }

        public string RequiredErrorMessage
        {
            get
            {
                this.EnsureChildControls();
                return __reqdErrMsg;
            }
            set
            {
                this.EnsureChildControls();
                __reqdErrMsg = value;
            }
        }

        #endregion
                
        #region overridden methods load, init and pre render
                protected override void OnLoad(EventArgs e)
                {
                    lblCaption.Text = Caption;

                    base.OnLoad(e);
                }

                protected override void OnInit(EventArgs e)
                {
                    if (!Required)
                        regVal.Visible = false;

                    if (MaxLength > 0)
                        txtInput.MaxLength = MaxLength;

                    if (!string.IsNullOrEmpty(ValidationGroup))
                    {
                        txtInput.ValidationGroup = ValidationGroup;
                        regVal.ValidationGroup = ValidationGroup;
                        cvCustomVal.ValidationGroup = ValidationGroup;
                    }

                    cvCustomVal.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(this.validator_ServerValidate);

                    base.OnInit(e);
                }

                protected override void OnPreRender(EventArgs e)
                {
                    base.OnPreRender(e);
                }

        #endregion

        #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

        #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

        
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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