Creating A Designer Enabled Custom Validator Control Pt. I
 
Published: 10 Feb 2004
Unedited - Community Contributed
Abstract
This is a two-part article. The first part of this article will discuss how to create server-side validation for your custom control and the second part will conclude with a discussion on how to complete your control by adding client-side validation to your control.
by King & Keith Wells
Feedback
Average Rating: 
Views (Total / Last 10 Days): 24476/ 38

Server-Side Validation

Creating A Designer Enabled Custom Validator Control

[DEMO]

By: Keith A Wells & King S Wells Jr.          

This is a two-part article. The first part of this article will discuss how to create server-side validation for your custom control and the second part will conclude with a discussion on how to complete your control by adding client-side validation to your control.

  PART I: Server-Side Validation

The new Microsoft .NET Framework has made the development of web based applications more structured and maintainable.  I have also discovered that there are many features that make web development easier but there are also features that make the development more difficult than in classical ASP. The use of object-oriented methodologies instead of the old spaghetti code provided in classical ASP is one such feature that makes development better when developing web applications using ASP.NET. Another feature in ASP.NET that makes development easier is the introduction of five new validation controls. The use of these five controls will cut down development time significantly.  I especially like the RegularExpressionValidator.  This validator is very flexible and meets many of the needs of the modern developer. The other four validation controls are the RequiredFieldValidator, CompareValidator, RangeValidator and CustomValidator. All of these controls play a significant role in cutting down on development time. But, as is often the case, we find that a development platform cannot always meet our needs or the needs of our customer. In such cases, we are required to develop our own solution. Because the development of a customized solution is often the case, I will show you how to develop a custom validator to address this need.  

Overview

 I have chosen to create a validator called the DualValidator. The concept for the DualValidator came from a validation requirement given to my brother by one of his customers.  In order to meet the deadline, we worked together on this particular requirement.

This customer required that either one of two controls may contain a value but not both. It was also required that the validator would only perform this test when a third control which I call the PrimaryControl contained a value. To summarize, this validator validated two controls based on the value contained in a third control.

In order to create a reusable custom validator, the control needs to be able to validate any control given to it. It is also a good idea to give the control the ability to be added to the designer’s toolbox.  One such designer is Visual Studio.NET.

Defining The TagPrefix

The TagPrefix is an assembly level attribute that allows you to automatically create a Register directive in your aspx page.

[assembly:TagPrefix("Southpoint.Framework.Validator", "val")]

An assembly-level attribute that allows you to define an alias for your control’s tag prefix.

  E.g.

 <%@ Register TagPrefix="val" Namespace="Southpoint.Framework.Validator" Assembly="DualValidator" %>

<meta content="True" >

[assembly:TagPrefix("Southpoint.Validator", "val")]

namespace Southpoint.Framework.Validator

{             /// <summary>

            /// Summary description for DualValidator.

            /// </summary>

Defining Toolbox Default Values

 If you want your control to have a meaningful tag when you drag your control onto a form, then you will need to define this tag by using the ToolboxAttribute attribute class. All attribute classes end with the word Attribute. But, when you are declaring your attribute, you may leave the word Attribute off.  See the example below.  

ToolboxData("<{0}:DualValidator runat=server></{0}:DualValidator>")

Or

 ToolboxDataAttribute("<{0}:DualValidator runat=server></{0}:DualValidator>")

  The ToolBoxDataAttribute  defines the default tag that is generated
when the control is dragged onto a web form.

E.g <val:Dualvalidator runat=server></val:DualValidator>

    

Server-Side Validation Page 2

Page 2

           [

            DefaultProperty("Text"),

            ToolboxData("<{0}:DualValidator runat=server></{0}:DualValidator>")

            ]

   Defining Validator

 The base class used for this control is the BaseValidator class. By inheriting from the BaseValidator class, you will have access to all of its properties and methods.
Some of the methods that you will have to override in this example are EvaluateIsValid
and the ControlPropertiesValid method.
The EvaluateIsValid is used to determine if the value being evaluated is valid or not. The ControlPropertiesValid method is used to determine whether the control defined in the ControlToValidate property is validatable.

            public class DualValidator : BaseValidator

            {
             
          string strFunctionName ;
                        public DualValidator() :base()

                        {           //

                                    // TODO: Add constructor logic here

                                    //                }

                           

TypeConverter

Shows the value of a property as text to the property browser. Also converts the text value to an object. 

ValidatedControlConverter

Converts the control to a string and shows the value to the designer as a control that can be validated by a validation control.

You can see in the dropdownlist below, a list of controls that can be validated by the validation control.

 

 

 

FIGURE 1

CategoryAttribute

This attribute defines where in the visual designer your property or event will appear. You can see in Figure 1 above that the PrimaryControl, FirstControlToValidate and the SecondControlToValidate are defined under the BEHAVIOR category group.                                                     

 CREATING NEW CONTROL PROPERTIES

 I have defined three new properties whose values can be set visually in the properties window of the designer. These three custom properties,the PrimaryControl, FirstControlToValidate and SecondControlToValidate will allow me to define the controls that I desire to validate within the web page.

 

Server Side Validation Page 3

VIEWSTATE

 These new properties will allow you to define validatable controls that can be used in your validation process. Since web applications cannot maintain state on its own, you will need a method to do so. Microsoft has provided us with a View State property to maintain state for a page and its controls. A View State is ideal for maintaining the data for a control as the application makes a trip to the server and back to the client. Usually data is lost when the application makes a round trip to the server but with the help of a View State , a control’s value is maintained during this round trip from the client to the server and back.

Each control inherits a View State property from the Control class that you can use when creating your new property within the validation control you are designing.

                    

[
    Category("Behavior"),
    DefaultValue(""),
    Description("The control that the first and second control is dependant on 
    when validating."),

    TypeConverter(typeof(ValidatedControlConverter))
 
                      public string PrimaryControl
                        {
                            get
                                    {
                                                object o = ViewState["PrimaryValue"];
                                                return (o==null) ? String.Empty : (string)o;
                                    }

                                    set
                                    {
                                                ViewState["PrimaryValue"] = value;
                                    }
                        }
               [
                   Category("Behavior"),
                   DefaultValue(""),
                   Description("The first control to validate."),
                   TypeConverter(typeof(ValidatedControlConverter))
               ]        
                      public string FirstControlToValidate

                        {
                                    get

                                    {
                                                object o = ViewState["FirstValue"];                                                 return (o==null) ? String.Empty : (string)o;                                     }

                                    set

                                    {
                                                ViewState["FirstValue"] = value;
                                    }
                        }  
                [

                   Category("Behavior"),
                   DefaultValue(""),
                   Description("The second control to validate."),
                   TypeConverter(typeof(ValidatedControlConverter))

                ]   
                        public string SecondControlToValidate

                        {
                            get

                            {
                                      object o = ViewState["SecondValue"];
                                      return (o==null) ? String.Empty : (string)o;
                            }
                                    set
                                    {
                                                ViewState["SecondValue"] = value;
                                    }
                        }

 

 [Browsable(false)]
Attribute which determines whether a property or event is visible in the properties browser window

 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

Makes the value of the property not visible to the property browser

 

Server Side Validation Page 4

DISABLING THE CONTROLTOVALIDATE PROPERTY

 My DualValidator uses the values from two controls that are identified via the FirstControlToValidate property and the SecondControlToValidate property.  Since I have no need of the ControlToValidate property, I have hidden it from the property browser of Visual Studio.NET and have also raised an exception if a user tries to set the property’s value in the codebehind file.

       /// Disable ControlToValidate.       

       [Browsable(false)]
       [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]  
                public new string ControlToValidate
                {
                  get { return "";
                }
                  set { throw new NotSupportedException("Assign ControlToValidate on FirstControlToValidate and SecondControlToValidate instead.");
                        }

                }
  /// Since we are not using ControlToValidate, this should always return true.

                        protected override bool ControlPropertiesValid()

                        { 
                          
return true;                             

                        }

 

EvaluateIsValid THE HEART OF SERVER-SIDE VALIDATION

 Normally, the EvaluateIsValid method is used to determine if the value in the ControlToValidate property is valid. However, in my case, I disabled the ControlToValidate property and created three new properties for validating. This validator validates the values in two controls if and only if the value in the third control had a value. The property called PrimaryControl is used to determine whether we will do any validation on the FirstControlToValidate and SecondControlToValidate properties.  In order to keep this method clean and easily readable, I created a new method called ValidateDualControls that actually performs the validation. It receives three parameters. These parameters contain the value for the three properties listed above, the PrimaryControl, FirstControlToValidate and SecondControlToValidate properties that represent the controls that are involved in the validation routine.
           

            protected override bool EvaluateIsValid()
                        {                                  

return     

            ValidateDualControls(this.PrimaryControl,this.FirstControlToValidate, this.SecondControlToValidate);

                        }
                        protected bool ValidateDualControls(string primarycontrol, string      

                                               control1, string control2)
                        {
                                    string FirstControl_Value = "";
                                    string SecondControl_Value = "";

 

 

Server Side Validation Page 5

 Naming Container – a new namespace is created that insures that the control Ids are unique within an application. Every server control has a NamingContainer property. You can use this property to locate a control within a page. A new instance of the Page class is the default NamingContainer for a newly requested page.  

Because my DualValidator class has defined three new properties, there must be a way to locate the controls associated with these properties and acquire access to the values of these controls. The NamingContainer allows me to do so by searching its namespace using the FindControl() method.

Our requirement only required that we validate two dropdownlist objects, but with a few more lines of code, you can enhance this code to dynamically determine which type of control you need to cast your object into and access its values appropriately.  

(partial code)

TextBox      PrimaryControl = ((TextBox)NamingContainer.FindControl(primarycontrol));

 DropDownList ControlValue1 = ((DropDownList)NamingContainer.FindControl(control1));

 DropDownList ControlValue2 = ((DropDownList)NamingContainer.FindControl(control2));

FirstControl_Value =  ControlValue1.SelectedItem.Value.ToString();
SecondControl_Value =   

                         ControlValue2.SelectedItem.Value.ToString();  

                   if (PrimaryControl.Text.Trim() != String.Empty)

                      {
                                    if (FirstControl_Value.Trim() == String.Empty &&                                      SecondControl_Value.Trim() == String.Empty)

                                      {
                                                return false;

                                      }                                      

                                    else if (FirstControl_Value.Trim() != String.Empty &&                                             SecondControl_Value.Trim() != String.Empty)

                                      {
                                                return false;

                                      }  

Conclusion

This article showed us how to create a custom validator control that can be used in any .NET visual IDE designer.  Every web developer needs to know how to provide his web application with validation capabilities. Although Microsoft has assisted us greatly in the area of validation, a professional developer cannot escape the need to develop his own custom validator. I hope this series of articles will assist you in acquiring this ability.

In the next article, King is going to show you how to give your validator the ability to validate using client-side validation.  

Copyright: 2003 Keith A Wells and King S Wells Jr.



User Comments

Title: Kevin-Rookie   
Name: JamesT
Date: 2009-01-08 1:51:13 PM
Comment:
Kevin, you are a rookie. A custom validation control is needed when the current controls do not meet your criteria.
Some validation rules are too complex and require custom handling.
Title: very very thanks   
Name: s/w eng. Rituraj pandey
Date: 2008-11-20 1:25:25 AM
Comment:
hi, i am very-2 thak full to you because this is a greated need to me and this is a great help to me so thank you.
Title: No   
Name: Kevin
Date: 2008-06-27 7:26:45 AM
Comment:
No, this is not helpfull. Why does every one want to increase the file size by creating custom validations as a script. Use the syntax when you assign the validation to a text box or field
Title: custom control   
Name: Rahul
Date: 2007-09-05 7:00:00 AM
Comment:
thnx give the best examples.so that we can learn more info abt custom validation.
Regards,
Rahul
Title: Code Download Available?   
Name: Edward
Date: 2007-07-02 12:35:39 PM
Comment:
Is the complete code download available?

Thanks,
Ed
Title: Microsoft Validation for Custom Controls?   
Name: Alfred
Date: 2005-11-04 12:13:57 PM
Comment:
Thank you for your article, I would like to ask you how to create user control that standard validation control can recognise it, that is UserControl name will appear in ControlToValidate list?
Thank you.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 8:13:42 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search