LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Validation in ASP.NET
by . .
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 32951/ 92


Validation in ASP.NET

Published 09/21/01 - For ASP.NET


When you have a form that user's submit data, its important that they don't mess it up and enter weird stuff. Validation stops this but in ASP it was a tedious job of If statements to work out. I myself had a simple form that added users to a database, it had a heck of a lot of if statements. ASP.NET introduces - Validation Controls. These controls are just like Web Controls and can do many things like - Check if a field is filled out, Compare a field to something (or another), Use regular expressions on a field, Check to see if a field is within a certain range, you can even create your own!

Before we begin

Now, this is going to be a pretty big article/tutorial so lets get some of the common stuff out first.

Validation Controls only work for the following controls:

  • HTMLInputText

  • HTMLTextArea

  • HTMLSelect

  • HTMLInputFile

  • TextBox

  • ListBox

  • DropDownList

  • RadioButtonList

But what other controls could you use it on? Yes there are many more, but its rather hard to do everything in one. Next, the control syntax takes the form of -

<asp:ControlName runat="Server" ControltoValidate="ControlName" ErrorMessage="Message" OtherProperties />

(Remember that the italics stuff is stuff that you change). Now its pretty obvious what ErrorMessage is (its the message that's displayed if it turns out that the field isn't valid). ControltoValidate is the id of the control that your going to be checking. One last thing, here is a page that I've created that uses Validator Controls. Try the following to see what errors come up:

  • Enter no name.
  • Enter only a first name.
Required Fields

Required Fields

This is the big one that takes out those input statements! It checks to see if the ControltoValidate has some sort of value in it, if it does have something, then its IsValid property is set to True.

Enter your name (First & Last): <asp:TextBox id="FName" runat="server" /><br>

<asp:RequiredFieldValidator runat="Server" ControltoValidate="FName" ErrorMessage="You didn't fill in your name"/>

If the user doesn't enter anything in the textbox, the message - "You didn't fill in your name" appears in Red where the Validator is. You can put validators anywhere and the message just appears there.

Using Regular Expressions

Regular Expressions

I never really got the hang of regular expressions, but I can do some very simple things. Now if your putting all of my code into a file to test it, just add this one below the last. Remember that you aren't limited to one validator per control, you can have as many as you like!

<asp:RegularExpressionValidator runat="Server" ControltoValidate="FName" ErrorMessage="Your name isn't in the correct format!" ValidationExpression="\S+\s\S+" />

Now this checks to see weather the field matches the pattern in the ValidationExpression property, in this case the pattern in - "Any number of non-space characters, followed by one space, followed by any number of non-space characters", this is the normal format for a name.

For more resources on regular expressions see -

Comparing Values

Comparing Data

This one compares data in one field to another field or to a constant (or a Data Type). It has several options which I will cover now.

  • Instead of ControltoCompare you can use ValuetoCompare if you want to use a constant value.
  • Operators can be one of the following:
    • DataTypeCheck
    • Equal
    • GreaterThan
    • GreaterThanEqual
    • LessThan
    • LessThanEqual
    • NotEqual
  • The Type property can be one of the following:
    • Currency
    • Date
    • Double
    • String
    • Integer

Here is the example:

First Name:<asp:textbox id="FName2" runat="server" />Last Name: <asp:TextBox id="LName2" runat="server" /><p>

<asp:CompareValidator runat="Server" ControltoValidate="FName2" ControltoCompare="LName2" Type="String" Operator="NotEqual" ErrorMessage="Your First Name can't be your last name as well!" />

This makes sure that your first name isn't your last name (don't complain if your first name is also your last name, this is just an example!).

Using Ranges


This lets you see if a value is between two ranges. The range (set in MinimumValue and MaximumValue can either be a string or number). This checks to see if a zip code is within a specified range, I also used a Regular Expression Validator to check it too.

Please Enter your Zip Code:<asp:textbox id="ZIP" runat="server" /><p>

<asp:RangeValidator runat="server" ControltoValidate="ZIP" ErrorMessage="Your Zip isn't within the range (8000 - 9000)!" MinimumValue="8000" MaximumValue="9000" />

<asp:RegularExpressionValidator runat="Server" ControltoValidate="ZIP" ErrorMessage="That Zip code is invalid (numbers only and 4 numbers long!)" ValidationExpression="[0-9]{4}|[0-9]{5}" />

The RangeValidator made sure that you kept the value between 8000 and 9000, the regular expression one made sure that it was 4 or 5 (someone would complain if it was only 4) numbers long and only numbers.

Custom Validation

Custom Validation

Creating your own validation isn't too hard, if you're no good a regular expressions then you can use this to do them. The following one makes sure that your entry is at least 8 letters long.

<script language="VB" runat="server">
Sub ValidateMe(sender as object, e as ServerValidateEventArgs)
     If Len(e.Value) > 8 Then
          e.IsValid = True
          e.IsValid = False
     End If
End Sub

Enter a username:<asp:textbox id="username" runat="server" /><p>

<asp:CustomValidator runat="server" OnServerValidate="ValidateMe" ControltoValidate="username" ErrorMessage="Username must be at least 8 letters long" />

Ok, the sub takes in the usual values, but it takes in ServerValidateEventArgs instead of EventArgs, this lets you get the value and set the IsValid Property. However this is server side validation (you'll learn more about why this is important soon), to make it client side, just add the property - "OnClientSideValidator="validating"". Then add some client side JavaScript to handle it (in the form of a function), otherwise it gets processed on the server.

But wait! There's more!

More? Yes! Here are some things that will add you your adventure's. Now obviously, having the Error text red all the time will get a bit annoying, so you can add the ForeColor = "Color" property to the control to change the error text color.

Now if you take all the code that I've given you on this page and put it into one file, add a submit button, form tags and then run it you will see that the Validation occurs with JavaScript and Span tags. This means that the page doesn't get submitted until the validators are satisfied with what you've put in. But you'll also see that there are gaps where the validators are on the page which are blank, they are activated when an error is found. You can set a Display property to change this -

  • Display = "None"    'No error message is displayed and the spaces are gone
  • Display = "Static"  'Default, spaces are left for the errors
  • Display = "Dynamic" 'Spaces are generated only if an error occurs.

You'll learn more about this in the next section.

When you submit the page, it doesn't go through until the validators are happy, when it is submitted, its checked again and a value - Page.IsValid is generated to tell you if all the validators are happy -

<script language="VB" runat="server" >
Sub Page_Load(sender as object, e as EventArgs)
If Page.IsPostBack Then
    If Page.IsValid Then
       lblMessage.Text = "You passed Validation"
    End If
End If
End Sub

<asp:label id="lblMessage" runat="server"/><p>


Validation Summaries


Now, if you want to take all the errors and put them in one place then you can with the ValidationSummary Control. This allows you to have a summary of all the errors. You can still have the in-line errors or you can turn them off by using the Display=none property. The following changes can be made to the script below:

  • DisplayMode can be - BulletList, List or SingleParagraph
  • ShowMessageBox can be - True. This shows a message box with the errors in them.
<asp:ValidationSummary DisplayMode="BulletList" HeaderText="The following errors were found on the page:" runat="server" />

This just brings up a summary of the errors.

Validation on the client side

Nearly there

This is what you can do with validation in ASP.NET and as you can see you can do a lot. If you go to my page here, or the page using this code here, then you can experiment with creating errors and seeing what happens (there are some source changes). The changes to the source are - some control's Display is none so it only appears in the Summary. You will also notice that with the CustomValidator, the validation will occur on the server, so you get the message "Validation Passed" and then the error, to fix that, use Client-Side Java-Script, as you can see -

...... OnClientSideValidate="Validating".....

<Script language="JavaScript">
  function validating( objSen, txtVal){
    var isvalid = True;
    if(txtVal.length < 8){
        isvalid = False;)}
    return isvalid


Ok, that is Validation for you. Its quite large, but I'm sure that you will use it. I know that it takes forever having to write in the control names and property names (Microsoft should do something about that, like aliasing them) but it could be worth it, and why can't the operator property use symbols - < > = <> <= >= etc.? But anyway, this is a tutorial not an MC.

Happy Validating!

Product Spotlight
Product Spotlight 

©Copyright 1998-2021  |  Page Processed at 2021-03-05 1:57:44 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search