R – Validation controls not applicable to web custom controls in asp.net

asp.netcustom-controlsvalidation

I have created a web custom control and used within an aspx page. I found the validation controls provided by asp.net are applicable to the built in server controls. I am not able to attach these validation controls with my custom control.

For ex. If i am using TextBox control then the RequiredFieldValidator is applicable to it. but when i try to apply the same RequiredFieldValidator to my custom control it is not possible. The property "ControlToValidate" does not show the object id of my custom control.

Could someone help me to rectify this problem?

Thanks for sharing your valuable time.


Below is the code from .cs file –

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;

[assembly: TagPrefix("DatePicker", "SQ")]
namespace DatePicker
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
    public class DatePicker : CompositeControl
    {
        //To retrieve value i am using textbox
        private TextBox _TxtDate = new TextBox();
        // Image to select the calender date
        private Image _ImgDate = new Image();
        // Image URL to expose the image URL Property
        private string _ImageUrl;
        // Exposing autopostback property 
        private bool _AutoPostBack;
        // property get the value from datepicker.
        private string _Value;
        //CSS class to design the Image
        private string _ImageCssClass;
        //CSS class to design the TextBox
        private string _TextBoxCssClass;
        //to formate the date
        private string _DateFormat = "%m/%d/%Y";
        //to hold javascript on client side
        static Literal _litJScript=new Literal();
        private bool _includeJS = false;

        /**** properties***/

        #region "[ Properties ]"
        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string ImageUrl
        {
            set
            {
                this._ImageUrl = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string Text
        {
            get
            {
                //String s = (String)ViewState["Text"];
                //return ((s == null) ? string.Empty : s);
                return _Value = _TxtDate.Text;
            }

            set
            {
                ViewState["Text"] = value;
                _TxtDate.Text = value;
                _TxtDate.BackColor = System.Drawing.Color.White;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string Value
        {
            get
            {

                return _Value= _TxtDate.Text;
            }

            set
            {
                _Value = _TxtDate.Text = value;
                ViewState["Text"] = _Value;
                _TxtDate.BackColor = System.Drawing.Color.White;
            }
        }
        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                return _AutoPostBack;
            }

            set
            {
                _AutoPostBack = value;
            }
        }
        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string ImageCssClass
        {
            get
            {
                return _ImageCssClass;
            }

            set
            {
                _ImageCssClass = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string TextBoxCssClass
        {
            get
            {
                return _TextBoxCssClass;
            }

            set
            {
                _TextBoxCssClass = value;
            }
        }

        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string CommandName
        {
            get
            {
                string s = ViewState["CommandName"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandName"] = value;
            }
        }

        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string CommandArgument
        {
            get
            {
                string s = ViewState["CommandArgument"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandArgument"] = value;
            }
        }
        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string DateFormat
        {
            get
            {
                return _DateFormat;
            }
            set
            {
                _DateFormat = value;
            }
        }

        [Bindable(true), Category("Behavior"), DefaultValue("True")]
        public bool IncludeClientSideJS
        {
            get { return _includeJS; }
            set {
                _includeJS = value;
            }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("True")]
        public override bool Enabled
        {
            get { return _TxtDate.Enabled; }
            set
            {
                _TxtDate.Enabled = value;
                _ImgDate.Visible = value;
            }
        }
        [Bindable(true), Category("Layout")]
        public override Unit Width
        {
            get
            {
                return base.Width;
            }
            set
            {
                base.Width = value;
                _TxtDate.Width = value;
            }
        }
        #endregion

        protected static readonly object EventCommandObj = new object();

        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommandObj, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommandObj, value);
            }
        }
        //this will raise the bubble event
        protected virtual void OnCommand(CommandEventArgs commandEventArgs)
        {
            CommandEventHandler eventHandler = (CommandEventHandler)Events[EventCommandObj];
            if (eventHandler != null)
            {
                eventHandler(this, commandEventArgs);
            }
            base.RaiseBubbleEvent(this, commandEventArgs);
        }
        //this will be initialized to  OnTextChanged event on the normal textbox
        private void OnTextChanged(object sender, EventArgs e)
        {
            if (this.AutoPostBack)
            {
                //pass the event arguments to the OnCommand event to bubble up
                CommandEventArgs args = new CommandEventArgs(this.CommandName, this.CommandArgument);
                OnCommand(args);
            }
        }

        protected override void OnInit(EventArgs e)
        {

            base.OnInit(e);
            AddStyleSheet();
            AddJavaScript("DatePicker.Resources.prototype.js");
            AddJavaScript("DatePicker.Resources.calendarview.js");

            // For TextBox
            // setting name for textbox. using t just to concat with this.ID for unqiueName
            _TxtDate.ID = this.ID + "t";
            // setting postback
            _TxtDate.AutoPostBack = this.AutoPostBack;
            // giving the textbox default value for date
            _TxtDate.Text = this.Value;
            //Initializing the TextChanged with our custom event to raise bubble event
            _TxtDate.TextChanged += new System.EventHandler(this.OnTextChanged);
            //Set max length
            _TxtDate.MaxLength = 10;
            //Setting textbox to readonly to make sure user dont play with the textbox
            //_TxtDate.Attributes.Add("readonly", "readonly");
            // adding stylesheet 
            _TxtDate.Attributes.Add("class", this.TextBoxCssClass);
            _TxtDate.Attributes.Add("onkeypress", "maskDate(event)");
            _TxtDate.Attributes.Add("onfocusout","isValidDate(event)");

            // For Image
            // setting alternative name for image
            _ImgDate.AlternateText = "imageURL";
            if (!string.IsNullOrEmpty(_ImageUrl))
                _ImgDate.ImageUrl = _ImageUrl;
            else
            {
                _ImgDate.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.CalendarIcon.gif");
            }

            //setting name for image
            _ImgDate.ID = this.ID + "i";
            //setting image class for textbox
            _ImgDate.Attributes.Add("class", this.ImageCssClass);

            //Initialize JS with literal
            string s = "<script language=\"javascript\">function maskDate(e){var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
            s = s + "var myT=document.getElementById(srcEle.id);var KeyID = evt.keyCode;";
            s = s + "if((KeyID>=48 && KeyID<=57) || KeyID==8){if(KeyID==8)return;if(myT.value.length==2){";
            s = s + "myT.value=myT.value+\"/\";}if(myT.value.length==5){myT.value=myT.value+\"/\";}}";
            s = s + "else{window.event.keyCode=0;}}";

            string s1 = "function isValidDate(e){var validDate=true;var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
            s1 = s1 + "var myT=document.getElementById(srcEle.id);var mm=myT.value.substring(0,2);var dd=myT.value.substring(5,3);var yy=myT.value.substring(6);";
            s1 = s1 + "var originalCss =myT.className; if(mm!=0 && mm>12){myT.value=\"\"; validDate=false;}else{if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0){if(mm==2 && dd>29){";
            s1 = s1 + "myT.value=\"\"; validDate=false;}}else{if(mm==2 && dd>28){myT.value=\"\"; validDate=false;}else{if(dd!=0 && dd>31){";
            s1 = s1 + "myT.value=\"\"; validDate=false;}else{if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){myT.value=\"\";  validDate=false;}}}}}";
            s1 = s1 + "if(!validDate){myT.style.backgroundColor='#FD9593';myT.focus;}else { myT.style.backgroundColor='#FFFFFF';}}</script>";


            _litJScript.Text = s+s1;
        }

        /// <summary>
        /// adding child controls to composite control
        /// </summary>
        protected override void CreateChildControls()
        {
            this.Controls.Add(_TxtDate);
            this.Controls.Add(_ImgDate);
            if(_includeJS)
                this.Controls.Add(_litJScript);
            base.CreateChildControls();

        }

        public override void RenderControl(HtmlTextWriter writer)
        {
             //render textbox and image
            _TxtDate.RenderControl(writer);
            _ImgDate.RenderControl(writer);
            if(_includeJS)
                _litJScript.RenderControl(writer);
            RenderContents(writer);

        }

        /// <summary>
        /// Adding the javascript to render the content 
        /// </summary>
        /// <param name="output"></param>
        protected override void RenderContents(HtmlTextWriter output)
        {
            StringBuilder calnder = new StringBuilder();
            //adding javascript first
            if (Enabled)
            {
                calnder.AppendFormat(@"<script type='text/javascript'>
                                     document.observe('dom:loaded', function() {{
                                        Calendar.setup({{
                                        dateField: '{0}',
                                        triggerElement: '{1}',
                                        dateFormat: '{2}'
                                     }})
                                    }});
                              ", _TxtDate.ClientID, _ImgDate.ClientID, _DateFormat);
                calnder.Append("</script>");
            }
            else
            {
                calnder.AppendFormat(@"<script type='text/javascript'>
                                     document.observe('dom:loaded', function() {{
                                        Calendar.setup({{
                                        dateField: '{0}',
                                        triggerElement: '{1}',
                                        dateFormat: '{2}'
                                     }})
                                    }});
                              ", _TxtDate.ClientID, null, _DateFormat);
                calnder.Append("</script>");
            }
            output.Write(calnder.ToString());
        }

        private void AddStyleSheet()
        {
            string includeTemplate = "<link rel='stylesheet' text='text/css' href='{0}' />";
            string includeLocation =
                  Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.calendarview.css");
            LiteralControl include = new LiteralControl(String.Format(includeTemplate, includeLocation));
            Page.Header.Controls.Add(include);
        }

        private void AddJavaScript(string javaScriptFile)
        {
            string scriptLocation = Page.ClientScript.GetWebResourceUrl(this.GetType(),javaScriptFile );
            Page.ClientScript.RegisterClientScriptInclude(javaScriptFile, scriptLocation);

        }

    }
}

Best Answer

You should either use a CustomValidator, or insert the RequiredFieldValidator directly into your custom control. Of course the built-in validators don't work with your control... they have no idea what to do with it! But if your control internally uses a TextBox, then you can also have a RequiredFieldValidator there.

A third possibility is to expose your internal TextBox with a property, which you can then reference with ControlToValidate. However, the first two methods are preferable.