Click here to Skip to main content
15,890,845 members
Articles / Web Development / ASP.NET
Article

Self Validating Text Box - 2

Rate me:
Please Sign up or sign in to vote.
4.50/5 (15 votes)
9 Feb 20044 min read 133.4K   1.1K   49   18
This article extends self validating Text Box control to other data types and Min and Max value checking.

Introduction

The motivation for this article lies at Self Validating ASP.NET Text Box by Patrick Meyer of NASA in Mission Planning Systems. Please read this excellent article for the self-validating control first. Like many other .NET developers, I like self-validating controls due to their simplicity. Microsoft provides CompareValidator and it serves the same purpose in general. Through self-validating control, I have to do less typing and there are less controls on the web form. This article validates the richness of .NET framework.

Pat showed us how to implement IValidator interface with a TextBox and I struggled to implement data type checking for various data types so that we do not need to implement different controls for various data types.

An excellent tool by Jay Freeman shortened my struggle to implement the same functionality as provided by CompareValidator. You can download this free tool from here. This tool goes through all Microsoft assemblies and somehow it converts IL code into C#. I looked how Microsoft implemented CompareValidator control and I used the same API for range and data type checking. It took me a little time to implement this. Through Jay's tool, you can peep through how great minds at Microsoft do the development.

I desire to have a self-validating TextBox control that can check if the field is a required field or not. This should also perform a min or max value validation by using MinValue and MaxValue properties of the TextBox. I should be able to specify the data type of the input in the text box. Since CompareValidator does this already, Anakrino tool helped me figure out how it was done internally. The data types implemented are String, Currency, Double, Date and Integer.

Implementing the Compare of BaseCompareValidator

After going through the source of various methods in BaseValidator, BaseCompareValidator and CompareValidator, I noticed that I could use BaseCompareValidator.CanConvert method to check the data type validity of the input data. I also need to check for the range or compare the input value for different data types against a given MinValue or MaxValue property of the control. If I define TextBox control to be a Date then my date should be within MinValue or MaxValue. If data type is Currency then my value cannot be greater than say 10,000.

A simple rule that I follow for MinValue or MaxValue is that if these values are blank then I do not need to perform a validation. In real life situation, we would like to bind MinValue and MaxValue to the database. I would recommend using two-way data binding approach for a web form in general. There is an excellent article on this topic here. If you use two-way data binding with self-validating TextBox in your real life projects, you do not have to type much code to unbind data.

We hope that ASP.NET "Whidbey" will implement two way data binding and that will reduce coding for generic type of web forms implementing typed DataSets.

To implement range checking, there is a protected method Compare in BaseCompareValidator class. Since I am already inheriting my TextBox class from System.Web.UI.WebControls.TextBox, C# will not allow multiple inheritance. I had to create another class to get the advantage of this protected method.

C#
public class EADCompare : BaseCompareValidator 
{ 
  public static bool DoCompare(string from, string to, 
     ValidationCompareOperator cmp, ValidationDataType objType) 
  { 
    if (to == null || to.Length == 0) return true; 
    return BaseCompareValidator.Compare(from, to, cmp, objType); 
  } 

  protected override bool EvaluateIsValid() 
  { 
     return true; 
  } 
}

The compiler forces you to implement EvaluateIsValid method. I just return true from this. We are not implementing this class in a true sense to implement a separate validator. We just want to access the Compare method to do the work instead of writing custom code.

To show a little graphic image along side with your text box when your validation fails is a neat idea. I borrowed this implementation by overriding Render method of TextBox as follows:

C#
protected override void Render(HtmlTextWriter writer)
{
    base.Render (writer);
    if (this.ErrorMessage != null && this.ErrorMessage != "" )
        writer.Write(" <img src=\"images/stop.gif\" alt=\"" + 
           this.ErrorMessage + "\")\">");
}

The error message shows up when you hover your mouse on this image. All other validation messages show up in the validation summary control as if you have used Microsoft provided validator controls. Please read Patrick’s article for details.

The validate method of the TextBox provides Required, MinValue and MaxValue validation against data types String, Currency, Double, Date and Integer.

C#
public void Validate()
{
   this.IsValid = true;
   bool isBlank = (this.Text.Trim() == "");
   if (Required)
   {
      if (isBlank)
      {
          this.ErrorMessage = 
            String.Format("'{0}' is a required field.", 
            this.UserFieldName);
          this.IsValid = false;
      }
    }
    if (!isBlank)
    {
         // if not blank then check the datatype of the control.
         bool isOk = 
           BaseCompareValidator.CanConvert(this.Text,GetDataType());
         if (!isOk)
         {
            this.ErrorMessage = 
              String.Format("'{0}' is not a valid data type.", 
              this.UserFieldName);
            this.IsValid = false;
            return;
          }
          // If MinValue is not empty then check if Text is less
          // than MinValue. If yes, validate false.
          isOk = EADCompare.DoCompare(this.Text, MinValue, 
            ValidationCompareOperator.GreaterThanEqual,GetDataType());
          if (!isOk)
          {
             this.ErrorMessage = String.Format("'{0}' " + 
               "can not have value less than {1}", 
               this.UserFieldName, this.MinValue);
             this.IsValid = false;
             return;
           }
           // If MaxValue is not empty then check if Text
           // is more than MinValue. If yes, validate false.
           isOk = EADCompare.DoCompare(this.Text, MaxValue, 
                     ValidationCompareOperator.LessThanEqual, 
                     GetDataType());
           if (!isOk)
           {
              this.ErrorMessage = String.Format("'{0}' " + 
                "can not have value more than {1}", 
                this.UserFieldName, this.MaxValue);
              this.IsValid = false;
              return;
            }
       }
}
ASP.NET
< %@Register TagPrefix="EAD" Namespace="EAD.WebControls" Assembly="General" % > 

To use this TextBox control in your web form, you need to first register the control in your ASPX page. Replace the name of the namespace and assembly, if you put this TextBox class in your favorite namespace and assembly.

A typical syntax of the TextBox in your page will look like this:

ASP.NET
<asp:label id="txtErrorMessage" runat="server" 
    EnableViewState="False"></asp:label>
<EAD:TextBox id="TextBox1" runat="server" UserFieldName="Double Test" 
   Required="False" MinValue="123.456" MaxValue="789023.345" 
   TextType="Double"></EAD:TextBox>
<EAD:TextBox id="Textbox2" runat="server" Width="64px" 
   UserFieldName="Date Test" Required="True" MaxValue="12/12/2000" 
   MinValue="1/1/2000" TextType="Date"></EAD:TextBox>
<EAD:TextBox id="Textbox3" runat="server" Width="64px" 
   UserFieldName="Integer Test" Required="True" MaxValue="100" 
   MinValue="10" TextType="Integer"></EAD:TextBox>
<EAD:TextBox id="Textbox4" runat="server" Width="64px" 
   UserFieldName="Currency Test" Required="True" MaxValue="12,000" 
   MinValue="10,000" TextType="Currency"></EAD:TextBox>
<EAD:TextBox id="Textbox5" runat="server" Width="64px" 
   UserFieldName="String Test" Required="False" MaxValue="P" 
   MinValue="B" TextType="String"></EAD:TextBox>

The attached ZIP file has three files. They are a sample ASPX page, TextBox class and Stop.gif image. The sample page has five different types of validations using different data types.

The screen capture is below:

Sample screenshot

Summary

Self validating controls give you flexibility to attach simple validation at the control itself. The same approach can be extended to other types of web controls. It should be fairly simple and straight forward.

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


Written By
Web Developer
United States United States
Vikram is an Enterprise Application Architect specializing in EAI, ETL, all relational databases and transforming legacy applications to Microsoft .Net environment. Vikram works for a consulting firm in Research Triangle Park, NC. Vikram has expertise in all relational databases, Cobol, mainframe, OO programming, C, Perl and Linux. C# is a newfound craze for Vikram.

Comments and Discussions

 
GeneralShow Message box Pin
Ngo Xuan Chuong28-Dec-07 20:13
Ngo Xuan Chuong28-Dec-07 20:13 
GeneralThis same control in VB [modified] Pin
brantpeery28-Jul-06 11:03
brantpeery28-Jul-06 11:03 
GeneralDoes not support ValidationGroup Pin
Sire40412-Apr-05 1:41
Sire40412-Apr-05 1:41 
GeneralRe: Does not support ValidationGroup Pin
Anonymous8-Jun-05 5:53
Anonymous8-Jun-05 5:53 
GeneralRe: Does not support ValidationGroup Pin
foosball31610-Feb-06 12:21
foosball31610-Feb-06 12:21 
AnswerRe: Does not support ValidationGroup Pin
Marcelo Godoy21-Dec-06 0:01
Marcelo Godoy21-Dec-06 0:01 
QuestionRe: Does not support ValidationGroup [modified] Pin
tumay10-May-07 8:20
tumay10-May-07 8:20 
GeneralRe: Does not support ValidationGroup Pin
DaveOMacalroy24-Jul-07 1:28
DaveOMacalroy24-Jul-07 1:28 
GeneralRe: Does not support ValidationGroup [Solution] (Kludge but it works) Pin
Sean Savelli7-Sep-07 3:40
Sean Savelli7-Sep-07 3:40 
GeneralRe: Does not support ValidationGroup [Solution] (Kludge but it works) Pin
taliesins30-Jul-08 4:48
taliesins30-Jul-08 4:48 
GeneralAbout Image Position &amp; Page Load Pin
Hemant Mane20-Feb-05 2:47
Hemant Mane20-Feb-05 2:47 
GeneralImage not past behind TextBox Pin
serg_bor1-Feb-05 19:23
serg_bor1-Feb-05 19:23 
GeneralClientValidationFunction Pin
dietrich22-Jun-04 12:14
dietrich22-Jun-04 12:14 
GeneralTrying to enhance control and/or rewrite in VB Pin
dokmanov14-Apr-04 17:58
dokmanov14-Apr-04 17:58 
Being more confortable with VB than C#, I started out by running the C# code for the control through a C# to VB translator. After minor tweeks, I ran the cod and all appeared to work.

Then I decided that I preferred that the TextType property be of type ValidationSummaryType rather than String so I could set the value of the property in the Properties Window by selecting a value in the dropdown list. I did this, and this worked.

I then for the first time added a ValidationSummary control to the form and got the following error:

Object reference not set to an instance of an object.

Damned if I knew why, so I decided to revert back to the original C# code and run it. This worked fine in all respects, except I then decided to make the same Enum change to it for the TextType property.

I changed the module level declaration to this:
private
System.Web.UI.WebControls.ValidationDataType _textType = System.Web.UI.WebControls.ValidationDataType.String;

and modified the property to this:

public ValidationDataType TextType
{
get { return this._textType; }
set { this._textType = value; }
}

But when I compiled and went to modify the property viw the Properties Window, there was no drop down list of enum values to select! Granted I don't know C#, but I expected this to work!


Ideally, I'd like to get my VB version working. Here it is if someone wants to try:
Imports System
Imports System.Data
Imports System.Drawing
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports System.Reflection


Namespace EAD.WebControls

#Region "TextBox Control"
<toolboxbitmap(gettype(textbox)), defaultproperty("text"),="" toolboxdata("<{0}:textbox="" runat="server" size="20">")> _
Public Class TextBox

Inherits System.Web.UI.WebControls.TextBox

Implements IValidator

Private _valid As Boolean = True
Private _errorMessage As String = ""
Private _required As Boolean = False
Private _minValue As String = String.Empty
Private _maxValue As String = String.Empty
Private _value As String = String.Empty
Private _textType As ValidationDataType = ValidationDataType.String
Private _userFieldName As String = String.Empty

Protected Overrides Sub OnInit(ByVal e As EventArgs)
MyBase.OnInit(e)
Page.Validators.Add(Me)
End Sub 'OnInit

Protected Overrides Sub OnUnload(ByVal e As EventArgs)
If Not (Page Is Nothing) Then
Page.Validators.Remove(Me)
End If
MyBase.OnUnload(e)
End Sub 'OnUnload

<category("data"), description("supported="" type="" are="" string,="" currency,="" double,="" date,="" integer"),="" defaultvalue("number")=""> _
Public Property DataType() As ValidationDataType
Get
Return _textType
End Get
Set(ByVal Value As ValidationDataType)
_textType = Value
End Set
End Property

<category("data"), description("the="" minimum="" threshold="" value="" that="" can="" be="" assigned="" to="" the="" control.="" if="" this="" is="" empty="" then="" check="" not="" performed.")=""> _
Public Property MinValue() As String
Get
Return _minValue
End Get
Set(ByVal Value As String)
_minValue = Value
End Set
End Property

<category("data"), description("the="" maximum="" threshold="" value="" that="" can="" be="" assigned="" to="" the="" control.="" if="" this="" is="" empty="" then="" check="" not="" performed.")=""> _
Public Property MaxValue() As String
Get
Return _maxValue
End Get
Set(ByVal Value As String)
_maxValue = Value
End Set

End Property

<category("data"), description("the="" value="" that="" is="" assigned="" to="" the="" number="" text="" field.")=""> _
Public Property Value() As String
Get
Return _value
End Get
Set(ByVal Value As String)
_value = Value
End Set
End Property

<category("data"), description("the="" error="" validator="" message="" that="" will="" be="" reported="" to="" the="" summary."),="" defaultvalue("")=""> _
Public Property ErrorMessage() As String
Get
Return _errorMessage
End Get
Set(ByVal Value As String)
_errorMessage = Value
End Set
End Property

<category("data"), description("set="" to="" true="" if="" you="" need="" this="" be="" a="" required="" field."),="" defaultvalue(false)=""> _
Public Property Required() As Boolean
Get
Return _required
End Get
Set(ByVal Value As Boolean)
_required = Value
End Set
End Property

<category("data"), description("the="" name="" of="" the="" label="" control."),="" defaultvalue("")=""> _
Public Property UserFieldName() As String
Get
If Me._userFieldName = [String].Empty Then
Me._userFieldName = Me.ID.Replace("txt", "")
End If
Return Me._userFieldName
End Get
Set(ByVal Value As String)
Me._userFieldName = Value
End Set
End Property

Public Property IsValid() As Boolean Implements System.Web.UI.IValidator.IsValid
Get
Return _valid
End Get
Set(ByVal Value As Boolean)
_valid = Value
If Not _valid Then
Me.BackColor = Color.OrangeRed
Else
Me.BackColor = Color.White
End If
End Set
End Property


Public Sub Validate() Implements IValidator.Validate

Me.IsValid = True

Dim isBlank As Boolean = Me.Text.Trim() = ""

If Required Then
If isBlank Then
Me.ErrorMessage = [String].Format("'{0}' is a required field.", Me.UserFieldName)
Me.IsValid = False
End If
End If
If Not isBlank Then
' if not blank then check the datatype of the control.
Dim isOk As Boolean = BaseCompareValidator.CanConvert(Me.Text, DataType())
If Not isOk Then
Me.ErrorMessage = [String].Format("'{0}' is not a valid " & DataType.ToString & " data type.", Me.UserFieldName)
Me.IsValid = False
Return
End If
' If MinValue is not empty then check if Text is less than MinValue. If yes, validate false.
isOk = EADCompare.DoCompare(Me.Text, MinValue, ValidationCompareOperator.GreaterThanEqual, DataType())
If Not isOk Then
Me.ErrorMessage = [String].Format("'{0}' can not have value less than {1}", Me.UserFieldName, Me.MinValue)
Me.IsValid = False
Return
End If
' If MaxValue is not empty then check if Text is more than MinValue. If yes, validate false.
isOk = EADCompare.DoCompare(Me.Text, MaxValue, ValidationCompareOperator.LessThanEqual, DataType())
If Not isOk Then
Me.ErrorMessage = [String].Format("'{0}' can not have value more than {1}", Me.UserFieldName, Me.MaxValue)
Me.IsValid = False
Return
End If
End If
End Sub 'Validate

'
' Override this method to provide error information
'

' <param name="writer" />
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
MyBase.Render(writer)

If Not (Me.ErrorMessage Is Nothing) And Me.ErrorMessage <> "" Then
writer.Write((" "))
End If
End Sub 'Render

Public Property ErrorMessage1() As String Implements System.Web.UI.IValidator.ErrorMessage
Get

End Get
Set(ByVal Value As String)

End Set
End Property



End Class 'TextBox
#End Region

#Region "EAD Compare"

Public Class EADCompare

Inherits BaseCompareValidator

Public Shared Function DoCompare(ByVal from As String, ByVal [to] As String, ByVal cmp As ValidationCompareOperator, ByVal objType As ValidationDataType) As Boolean
If [to] Is Nothing Or [to].Length = 0 Then
Return True
End If
Return BaseCompareValidator.Compare(from, [to], cmp, objType)
End Function 'DoCompare

Protected Overrides Function EvaluateIsValid() As Boolean
Return True
End Function 'EvaluateIsValid

End Class 'EADCompare

#End Region

End Namespace 'EAD.WebControls

'THanks for reading this
GeneralIt does not work in usercontrol Pin
tzarski11-Mar-04 0:33
tzarski11-Mar-04 0:33 
GeneralCouldn't not found EAD.WebControls Pin
Mohammed Nayeem16-Feb-04 23:14
Mohammed Nayeem16-Feb-04 23:14 
GeneralRe: Couldn't not found EAD.WebControls Pin
vikramk17-Feb-04 2:23
vikramk17-Feb-04 2:23 
GeneralRe: Couldn't not found EAD.WebControls Pin
Mohammed Nayeem17-Feb-04 18:16
Mohammed Nayeem17-Feb-04 18:16 

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

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