Steve Wellens


This Blog is dedicated to programming in the .Net enviroment

CompareValidator’s Hidden Gem (It does data type validation)

Man is small and the .NET environment is vast. After years of working in the .NET environment, you can still find new and amazing features. A user on the Asp.Net forums posted this feature I had never discovered…so I thought I'd pass it along.

The CompareValidator is used to compare the value of data in a textbox but it can also validate the type of data entered into a textbox.

It can validate these types:

  • String
  • Integer
  • Date
  • Double
  • Currency

You have to set the Operator attribute to DataTypeCheck and the Type attribute to one of the above values.

Here's a link with the details:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basecomparevalidator.type.aspx

Here's an example:

<asp:TextBox ID="TextBoxInteger" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" 
    ControlToValidate="TextBoxInteger"
    Operator="DataTypeCheck" 
    Type="Integer" 
    ErrorMessage="Please enter an integer" />
<br />        
 
<asp:TextBox ID="TextBoxDate" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator2" runat="server" 
    ControlToValidate="TextBoxDate"
    Operator="DataTypeCheck" 
    Type="Date" 
    ErrorMessage="Please enter a valid Date" />

 

I hope someone finds this useful.

Steve Wellens

Comments

sirdneo said:

I agree with you that Man is small and the .NET environment is vast, I have been working on .Net for quite some time but still i was not aware of this feature. Thanks for sharing :)

# October 2, 2009 3:46 AM

Zack Jones said:

Awesome tip. I can use this on an app I'm working on right now. Thanks for sharing it.

# October 12, 2009 10:48 AM

madhab bhandari said:

good to know..I never noticed this feature. I can use this feature on my application now.

# November 19, 2009 11:34 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)