Click here to Skip to main content
Click here to Skip to main content

Creating Custom Required Field Validator Control that inherits the Syste.Web.UI.WebControls.RequiredFieldValidator control

, 11 Dec 2006
Rate this:
Please Sign up or sign in to vote.
The control that is created is used to validate textbox and on error it indicates the validated textbox with changed background color for better user interface

Introduction

Here I am presenting the custom web control that is used to validate the textbox values same as RequiredFieldValidator control of ASP.NET. As, I am developing asp.net application I have to validate the input values at client side and also at server side and also at the time of error I need to indicate the textbox with changed background color. This required facility is not provided by the RequiredFieldValidator control of ASP.NET. So, I developed a custom Required Field Validator control that does this work and also it inherits the RequiredFieldValidator control of ASP.NET

Features

This control provides the ability of highlighting the textbox at time of error with changed background color. It also provide the facility of checkin the length of the input value for the given defined value at the time of development.

Limitations

This control only validates the textboxes. Also, this control does not provide facility of validating reqular expressions like email or internet url.

How the control is developed

For developing this control I have used Web Control Library project and the language C# 2.0.

To develope this control I have inhireted the RequiredFieldValidatorControl as my custom controls base class and overrided few methods. I have overrided OnPreRender,OnInit and EvaludateIsValid methods. I have also created custom properties like OriginalErrorMessage,MaximumTextLength,MaximumTextLengthErrorMessage,OriginalBackcolor,TextBoxBackgroundColorOnError. Short description of each property is as follows:

1)OriginalErrorMessage: this property provides the original error messgae

2)MaximumTextLength: this property is used to check if user input exceed the required lenght or not (by default this property is set to 0 means no length check)

3)MaximumTextLengthErrorMessage:this property is used to store the error message which is displayed at time of MaximumTextLength validation fails.

4)OriginalBackColor:This property is used to set the original background color of the textbox when no error is occured.

5) TextBoxBackgroundColorOnError: This property is used for setting the validated textbox background color at the time of error.

In the OnPerRender method I am injecting the javascript for client side validation and also it sets the background color of textbox if error is occured. The name of validating function is RequiredFieldValidatorEvaluateIsValid which is the default when the RequiredFieldValidator control of ASP.NET is rendered.

In OnInit method I am getting the textbox that is going to be validated and also getting its default background color for setting it when there is no error.

Complete Code for the control

<BR> <BR>using System;<BR>using System.Collections.Generic;<BR>using System.ComponentModel;<BR>using System.Text;<BR>using System.Web;<BR>using System.Drawing;<BR>using System.Web.UI;<BR>using System.Web.UI.WebControls;
namespace CustomWebControlsLibrary<BR>{<BR>    [DefaultProperty("Text")]<BR>    [ToolboxData("<{0}:CustomRequiredFieldValidatorControl 
runat=server></{0}:CustomRequiredFieldValidatorControl>")]<BR>    public class CustomRequiredFieldValidatorControl : RequiredFieldValidator<BR>    {<BR>        <BR>        [Category("Behavior")]<BR>        [Description("Get or set the value of Maximum Text Length.")]<BR>        public int MaximumTextLength<BR>        {<BR>            get {<BR>                if (ViewState["MaximumTextLength"] != null)<BR>                {<BR>                    return int.Parse(ViewState["MaximumTextLength"].ToString());<BR>                }<BR>                else {<BR>                    return 0;<BR>                }<BR>            }<BR>            set {<BR>                ViewState["MaximumTextLength"] = value;<BR>            }<BR>        }
        
        public Color TextBoxBackgroundColorOnError<BR>        {<BR>            get {<BR>                if (ViewState["TextBoxBackgroundColorOnError"] != null)<BR>                {<BR>                    return (Color)ViewState["TextBoxBackgroundColorOnError"];<BR>                }<BR>                else {<BR>                    return System.Drawing.Color.LightGray;<BR>                }<BR>            }<BR>            set {<BR>                ViewState["TextBoxBackgroundColorOnError"] = value;<BR>            }<BR>        }
        private string OriginalErrorMessage<BR>        {<BR>            get {<BR>                if (ViewState["OriginalErrorMessage"] != null)<BR>                {<BR>                    return (string)ViewState["OriginalErrorMessage"];<BR>                }<BR>                else {<BR>                    return "Provide valid Value";<BR>                }<BR>            }<BR>            set {<BR>                ViewState["OriginalErrorMessage"] = value;<BR>            }<BR>        }
        <BR>        private Color OriginalBackgroundColor<BR>        {<BR>            get {<BR>                if (ViewState["OriginalBackgroundColor"] != null)<BR>                {<BR>                    return (Color)ViewState["OriginalBackgroundColor"];<BR>                }<BR>                else<BR>                    return Color.LightGray;<BR>            }<BR>            set {<BR>                ViewState["OriginalBackgroundColor"] = value;<BR>            }<BR>        }
        public string MaximumTextLengthErrorMessage<BR>        {<BR>            get {<BR>                if (ViewState["MaximumTextLengthErrorMessage"] != null)<BR>                {<BR>                    return (string)ViewState["MaximumTextLengthErrorMessage"];<BR>                }<BR>                else {<BR>                    return "Please enter valid value.";<BR>                }<BR>            }<BR>            set {<BR>                ViewState["MaximumTextLengthErrorMessage"] = value;<BR>            }<BR>        }<BR>        private bool IsOriginalBackColorSet<BR>        {<BR>            get {<BR>                if (ViewState["IsOriginalBackColorSet"] != null)<BR>                {<BR>                    return (bool)ViewState["IsOriginalBackColorSet"];<BR>                }<BR>                else {<BR>                    return false;<BR>                }<BR>            }<BR>            set {<BR>                ViewState["IsOriginalBackColorSet"] = value;<BR>            }<BR>        }<BR>        TextBox textBox = new TextBox();<BR>        protected override void OnInit(EventArgs e)<BR>        {<BR>            base.OnInit(e);<BR>            textBox = ((TextBox)(Page.FindControl(base.ControlToValidate)));<BR>            if (!IsOriginalBackColorSet)<BR>            {<BR>                OriginalErrorMessage = base.ErrorMessage;<BR>                OriginalBackgroundColor = textBox.BackColor;<BR>                IsOriginalBackColorSet = true;<BR>            }<BR>            <BR>        }
        protected override bool EvaluateIsValid()<BR>        {<BR>            string Value = base.GetControlValidationValue(base.ControlToValidate);<BR>            if (Value == "")<BR>            {<BR>                textBox.BackColor = TextBoxBackgroundColorOnError;<BR>                return false;<BR>            }<BR>            else if (MaximumTextLength > 0)<BR>            {<BR>                if (Value.Length > MaximumTextLength)<BR>                {<BR>                    textBox.BackColor = TextBoxBackgroundColorOnError;<BR>                    ErrorMessage = MaximumTextLengthErrorMessage;<BR>                    return false;<BR>                }<BR>                else {<BR>                    textBox.BackColor = OriginalBackgroundColor;<BR>                }<BR>            }<BR>            else {<BR>                textBox.BackColor = OriginalBackgroundColor;<BR>            }<BR>            return true;<BR>        }
        protected override void OnPreRender(EventArgs e)<BR>        {<BR>            base.OnPreRender(e);<BR>            string validatedcontrolclientid = base.GetControlRenderID(base.ControlToValidate);<BR>            string script = @"<script language="'javascript'"><BR>function RequiredFieldValidatorEvaluateIsValid(val){<BR>var value = ValidatorGetValue(val.controltovalidate);<BR>if(value == '')<BR>{<BR>    document.getElementById('" + validatedcontrolclientid + "').style.backgroundColor='" +<BR>                               ColorTranslator.ToHtml(TextBoxBackgroundColorOnError) + "';";<BR>            script += "document.getElementById('" + base.ClientID + "').innerHTML='" + OriginalErrorMessage + 
"';";<BR>            script+="return false;}";<BR>            script += "else{document.getElementById('" + validatedcontrolclientid + "').style.backgroundColor='" + 
ColorTranslator.ToHtml( OriginalBackgroundColor) + "';return true;}}</script>";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidationScript", script);<BR>        }<BR>    }<BR>}<BR><BR><BR>

Please let me know about any error or any bug in my code.

How to use the Code

To use this code just create a Web Control Library project. Paste the entire code from here and build the application and take the referrence of the created .dll file to you project to use this control.

Validating for fixed length set the property MaximumTextLength to required value and also set the MaximumTextLengthErrorMessage. You can also set the TextBoxBackgroundColorOnError. Otherwise the default value of "LightGary" color is returnred.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author


Comments and Discussions

 
AnswerSolution to Master pages Pinmemberwillie4321beast9-Jul-08 10:21 
GeneralValidator usability PinmemberMcCarpenter22-May-08 0:37 
GeneralRe: Validator usability PinmemberStiven3-Jul-08 11:59 
GeneralValidatorCallout on MS AJAX Toolkit PinmemberSteven Berkovitz12-Dec-06 4:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 12 Dec 2006
Article Copyright 2006 by JatinPrajapati
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid