Have a question? ask www.kenlet.com
Home  |  FAQ  |  About  |  Contact  |  View Source   
    My Hood
Edit My Info
View Events
Read Tutorials
Training Modules
View Presentations
Download Tools
Scan News
Get Jobs
Message Forums
School Forums
Member Directory
    Sign me up!
Post an Event
Submit Tutorials
Upload Tools
Link News
Post Jobs
Home >  Tutorials >  General ASP.NET >  ASP.NET Validator Controls
Add to MyHood
   ASP.NET Validator Controls   [ printer friendly ]
  Rating: 4.49 out of 5 by 45 users
  Submitted: 11/03/01
Andrew Ma ()

This tutorial gives a brief overview of how to use the ASP.NET Input Validation Controls.

Back when we had only ASP, developers who had to write webpages for forms knew that the most tedious part is writing code to validate the user input. User input had to be validated so that malicious use of the pages couldn't be achieve. User input had to be validated so that an incorrect piece of information would not be entered. User input had to be validated so that the information stored was standardized. Yeah, some people had libraries of ASP functions to validate common things such as postal codes (zip codes for you Americans), e-mail addresses, phone numbers, etc. The developers of ASP.NET saw the tedium in always having to check user input. They decided that to simplify our life by including validation controls.
ASP.NET validation controls also provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will preform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will preform server-side where necessary. This client-side/server-side detection and validation is done without extra work by the developer!

With ASP.NET, there are six(6) controls included. They are:
  • The RequiredFieldValidation Control
  • The CompareValidator Control
  • The RangeValidator Control
  • The RegularExpressionValidator Control
  • The CustomValidator Control

Validator Control Basics
All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. They are:
  • ControlToValidate - This value is which control the validator is applied to.
  • ErrorMessage - This is the error message that will be displayed in the validation summary.
  • IsValid - Boolean value for whether or not the control is valid.
  • Validate - Method to validate the input control and update the IsValid property.
  • Display - This controls how the error message is shown. Here are the possible options:
    • None (The validation message is never displayed.)
    • Static (Space for the validation message is allocated in the page layout.)
    • Dynamic (Space for the validation message is dynamically added to the page if validation fails.)

The RequiredFieldValidation Control
The first control we have is the RequiredFieldValidation Control. As it's obvious, it make sure that a user inputs a value. Here is how it's used:
Required field: <asp:textbox id="textbox1" runat="server"/>
<asp:RequiredFieldValidator id="valRequired" runat="server" ControlToValidate="textbox1"
    ErrorMessage="* You must enter a value into textbox1" Display="dynamic">*

In this example, we have a textbox which will not be valid until the user types something in. Inside the validator tag, we have a single *. The text in the innerhtml will be shown in the controltovalidate if the control is not valid. It should be noted that the ErrorMessage attribute is not what is shown. The ErrorMessage tag is shown in the Validation Summary (see below).

The CompareValidator Control
Next we look at the CompareValidator Control. Usage of this CompareValidator is for confirming new passwords, checking if a departure date is before the arrival date, etc. We'll start of with a sample:

Textbox 1: <asp:textbox id="textbox1" runat="server"/><br />
Textbox 2: <asp:textbox id="textbox2" runat="server"/><br />
<asp:CompareValidator id="valCompare" runat="server"
    ControlToValidate="textbox1" ControlToCompare="textbox2"
    ErrorMessage="* You must enter the same values into textbox 1 and textbox 2"

Here we have a sample where the two textboxes must be equal. The tags that are unique to this control is the ControlToCompare attribute which is the control that will be compared. The two controls are compared with the type of comparison specified in the Operator attribute. The Operator attribute can contain Equal, GreterThan, LessThanOrEqual, etc.
Another usage of the ComapareValidator is to have a control compare to a value. For example:

Field: <asp:textbox id="textbox1" runat="server"/>
<asp:CompareValidator id="valRequired" runat="server" ControlToValidate="textbox1"
    ErrorMessage="* You must enter the a number greater than 50" Display="dynamic">*

The data type can be one of: Currency, Double, Date, Integer or String. String being the default data type.

The RangeValidator Control
Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.

Enter a date from 1998:
<asp:textbox id="textbox1" runat="server"/>
<asp:RangeValidator id="valRange" runat="server"
    ErrorMessage="* The date must be between 1/1/1998 and 12/13/1998" Display="static">*</asp:RangeValidator>

The RegularExpressionValidator Control
The regular expression validator is one of the more powerful features of ASP.NET. Everyone loves regular expressions. Especially when you write those really big nasty ones... and then a few days later, look at it and say to yourself. What does this do?
Again, the simple usage is:

E-mail: <asp:textbox id="textbox1" runat="server"/>
<asp:RegularExpressionValidator id="valRegEx" runat="server"
    ErrorMessage="* Your entry is not a valid e-mail address."

Here is a webpage I like to use to check my regular expressions.

The CustomValidator Control
The final control we have included in ASP.NET is one that adds great flexibility to our validation abilities. We have a custom validator where we get to write out own functions and pass the control value to this function.

Field: <asp:textbox id="textbox1" runat="server">
<asp:CustomValidator id="valCustom" runat="server"
    ErrorMessage="*This box is not valid" dispaly="dynamic">*

We notice that there are two new attributes ClientValidationFunction and OnServerValidate. These are the tell the validation control which functions to pass the controltovalidate value to. ClientValidationFunction is usually a javascript funtion included in the html to the user. OnServerValidate is the function that is server-side to check for validation if client does not support client-side validation.
Client Validation function:
<script language="Javascript">
    /* ... Code goes here ... */

Server Validation function:
Sub ServerValidate (objSource As Object, objArgs As ServerValidateEventsArgs)
    ' Code goes here
End Sub

Validation Summary
ASP.NET has provided an additional control that complements the validator controls. This is the validation summary control which is used like:

<asp:ValidationSummary id="valSummary" runat="server"
    ShowSummary="true" DisplayMode="List" />

The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list. The list can be either shown on the web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True")

Now you know how to use the Validator Controls in ASP.NET! Have fun!
I will also upload a sample of all the validator controls to the code sample section.

Acknoledgment: Professional ASP.NET (published by Wrox) was used a reference. It's a good book!

Tips to remember
  • If you are doing server-side validation, make sure the button onclick method has a Page.IsValid if statement or it will look like your validators aren't doing anything
  • Don't forget to wrap everything in the <form runat=server> tag.

Return to Browsing Tutorials

Email this Tutorial to a Friend

Rate this Content:  
low quality  1 2 3 4 5  high quality

Reader's Comments Post a Comment
Oops.... Errata:
for the Compare validator, it says Operator="Equals" when it should be Operator="Equal" (no s)
-- Andrew Ma, November 09, 2001
Sample code uploaded to devhood.
-- Andrew Ma, November 20, 2001
Great... this will clean up SOOO much of my sloppy JavaScript validating code that's always a pain to write.
-- D P, November 29, 2001
wow!...It's always a pain to write Javascripts to validate user input!
Now, I see the power of ASP.NET! Thanks for a great overview!
-- Stacey Chau, December 01, 2001
I'm about 50% through writing a robust error-checker for JavaScript that should be as easy to use as the .NET framework or whatever it's called. Here are some examples of how it would work:

<script language="javascript" src="js/error.js"></script>

<script language="javascript">
makeRequired('sample1', Email Address', 'email');
makeRequired('sample1', 'Social Security Number, 'SSN');

addCheck('sample1', 'Email Address', IS_EMAIL, 'email');
addCheck('sample1', 'Social Security Number', IS_SSN, 'SSN');

<form name="sample1" onsubmit="return validate('sample1')" method="get" action="(whatever)">
Email Address:<br>
<input type="text" name="email" size="50"><br><br>

Social Security Number:<br>
<input type="text" name="SSN"><br><br>

<input type="submit">

Do you think .NET makes this obsolete, or should I keep doing development? I know I would prefer the JavaScript version if I was a user, because that way you don't have to wait for an error page to load... you get feedback immediately. What are your thoughts?
-- Matt Sgarlata, December 20, 2001
Yes, unfortunately the .NET framework will make your stuff obselete.
ASP.NET is really cool because what it does is it has both client-side and server-side validation. It will detect which browser you have and if it supports client-side validation, it will use client-side. If not, then it will do server-side validation. You can also force it to do either, regardless of the browser.
-- Andrew Ma, January 05, 2002
-- Siyan Li, January 12, 2002
Is there a simple way to give a condition when a field is to be validated, or would that have to be done with a CustomValidator? ie if there are two submit buttons and the form requirements differ according to which button is clicked...
-- Anonymous Person, January 17, 2002
Waiki, you could use a CustomValidator to make sure certain conditions check out first, implementing them in client- and/or server-side script. You could also programmatically add validators, but this gets messy.
-- Heath Stewart, January 26, 2002
I would like to add that everything but CustomValidators (with proper implementation) *won't* work for drop-down controls. The reason is that there is not property to get the currently selected text as with other Forms controls. Even if you use MyDropDown.SelectedItem.Value, this won't work either. See the .NET docs for more information, but basically it's because the property SelectedIndex always returning a particular value.

In order to validate drop-downs, use Request.Form["mydropdown"] to get the text, if there is any. Make sure you check if the return is null before you try to access any methods or properties on the string object.
-- Heath Stewart, January 26, 2002
Yeah, this tutorial helps me a lot. Again, thanks.
-- Yusno Yunos, February 07, 2002
Good tutorial.
-- Brian Simoneau, April 15, 2002
There is a problem related to viewstate if you're trying to use validators along with server.Execute statements. In my case, I have a header aspx file that needs to execute some code in it's corresponding .vb file. When I do server.execute (can't use the <@ page > directive on #INCLUDE) the postback returns an error stating that the viewstate is invalid. Ugh.
-- Shane Pilo, May 03, 2002
Very nice tutorial Andrew. THere was a lot of thinking that went into .NET and I like how they have regular expression validation built in.. and then the whole custom thing is awesome.
-- Victor Vuong, June 04, 2002
good tutorial
-- Kyoungjin Park, November 05, 2002
Thank you so much! I forgot the Page.IsValid, and i spent hours to find the error, ahhh, thanks!
-- Svein Erik Storkaas, September 08, 2004
Oops - I see a typo "dispaly" should read "display"
-- John Pol, December 02, 2004
I would just like to state that you can use validation controls on drop down boxes. Just set the first value to "" and text to select something and it will validate.
-- mark samford, February 18, 2005
Regarding the email validation expression, using stars isn't a very good idea. When you use * it also grabs empty strings which shouldn't be allowed in an email-form. Use + instead which is similar to the star. The difference is that it requires at least one character to be entered. If you also want to filter out erronous characters you could use this expression:


(taken from an article at www.devarticles.com)

This might be a little bit difficult to remember or even understand if you're a beginner with regular expressions (take some time and learn if that's the case... it's not very difficult and doesn't take very long), so if you want a simpler one, you should use ".+@.+\..+" instead.
-- Joakim Carlsson, June 20, 2005
No comment
-- Josef Pazderka, October 03, 2005
When using RegEx it would be best to use the beginning (^) and end ($) anchors. Else the expression could match in the middle of something else that was not valid. (Reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/paght000001.asp)
-- James Bromley, December 19, 2005
Copyright © 2001 DevHood® All Rights Reserved