ASP 101 - Active Server Pages 101 - Web04
The Place ASP Developers Go!

Please visit our partners


Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates














ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash


 Top ASP 101 Stories Top ASP 101 Stories
VBScript Classes: Part 1 of N
Migrating to ASP.NET
Getting Scripts to Run on a Schedule

QUICK TIP:
HTTP Status Codes
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Form Validation

by John Peterson

Introduction

In our last lesson, we introduced you to the concept of viewstate and explained how ASP.NET makes managing it much easier. While we're on the topic of basic forms and how ASP.NET makes dealing with them easier, it's time to talk about another "V" word - validation.

What is Validation?

Validation is basically the act of comparing something to a given set of rules and determining if it satisfies the criteria those rules represent. In this case, the something that we are tring to validate is the input that a visitor to our site has entered into a web form.

There are a number of reasons why we'd want to do this. Some basic examples are:

  • No data or incomplete data was entered
  • The value of the data entered is not within the appropriate range
  • The format of the entered data is not as expected

There are any number of explanations why one of the above might occur. Perhaps a spider or web-bot has come across our form and tried to submit it without entering any data, maybe the user entered a item that doesn't really exist (ie. Feb. 29, 2002), or maybe they simply made a typo (ie. forgot to enter one of the digits in their phone number). Whatever the reason, the best course of action is usually easiest to determine if you know there is a problem while the user is still available to fix it.

Form Validation to the Rescue

That's why the concept of form validation became so popular so fast. If the type of data you're expecting to receive is relatively specific, there's no reason you can't set up a set of rules by which you can validate the data you receive right as the user is giving it to you. Assuming you can't make the correction automatically, still having the user available allows you to ask them to review their submission. After all, computers are very precise, but they're not all that smart. It's often easier for the user to fix whatever's causing the error then it is for the computer to do so.

ASP.NET Validation Controls

Okay so now that you have an idea of what form validation is, it's time to see how ASP.NET makes it easier then it's ever been before. The key to validation in the .NET world is a set of controls called validation controls (who'd have guessed).

There are 5 types of individual validation controls. They are:

  • RequiredFieldValidator
  • CompareValidator
  • RangeValidator
  • RegularExpressionValidator
  • CustomValidator

The Required Field Validator makes sure the user enters something. It doesn't have to be anything in particular, but they can't leave the field blank. The Compare Validator and the Range Validator both compare things using equality comparisons (the is x>=y type of thing). They only differ in that the Compare Validator is one-sided while the Range Validator allows you to specify both a lower and an upper bound. The Regular Expression Validator validates input against a regular expression. And if nothing else works for you, you can write your own criteria and encapsulate it in a Custom Validator.

In addition to these individual validation controls, there's one more kind: the Validation Summary control. This control is a great little touch by the folks from Redmond and allows you to easily check if every validator on a page is satisfied or not instead of having to check them all individually.

Let's See Some Code

Here's a simple sample which utilizes a Required Field Validator to make sure the user enters something for a name:

required.aspx

<%@ Page Language="VB" %>
<script runat="server">
    Sub btnSubmit_Click(Sender As Object, E As EventArgs)
        ' Do Something
    End Sub
</script>

<html>
<head>
<title>ASP.NET Form Validation Sample - Required Field Validator</title>
</head>
<body bgcolor="#FFFFFF">

<p>
Note that this form doesn't actually do anything
except illustrate the Required Field Validator.
</p>

<form id="frmValidator" action="required.aspx"
    method="post" runat="server">

    Enter Your Name:
    <asp:TextBox id="txtName" runat="server" />
    <asp:RequiredFieldValidator id="valTxtName"
        ControlToValidate="txtName"
        ErrorMessage="Please enter your name!"
        runat="server" />

    <br />

    <asp:button id="btnSubmit" text="Submit"
        onClick="btnSubmit_Click" runat="server" />

</form>

<p>
Hint: Try submitting it before you enter something.
</p>

</body>
</html>

Since I realize that's pretty boring, here's another sample... this time of the Range Validator:

range.aspx

<%@ Page Language="VB" %>
<script runat="server">
    Sub btnSubmit_Click(Sender As Object, E As EventArgs)
        ' Do Something
    End Sub
</script>

<html>
<head>
<title>ASP.NET Form Validation Sample - Range Validator</title>
</head>
<body bgcolor="#FFFFFF">

<p>
Note that this form doesn't actually do anything
except illustrate the Range Validator.
</p>

<form id="frmValidator" action="range.aspx"
    method="post" runat="server">

    Enter Your Age:
    <asp:TextBox id="txtAge" runat="server" />
    <asp:RequiredFieldValidator id="valTxtAgeReq"
        ControlToValidate="txtAge"
        ErrorMessage="Please enter your age!"
        Display="Dynamic"
        runat="server" />
    <asp:RangeValidator id="valTxtAgeRange"
        ControlToValidate="txtAge"
        Type="Integer"
        MinimumValue="21"
        MaximumValue="100"
        ErrorMessage="You need to be over 21 and under 100!"
        Display="Dynamic"
        runat="server" />

    <br />

    <asp:button id="btnSubmit" text="Submit"
        onClick="btnSubmit_Click" runat="server" />

</form>

<p>
Hint: Try entering an age under 21.
</p>

</body>
</html>

And here's one script that includes both at the same time and illustrates the basic use of the the Validation Summary control:

summary.aspx

<%@ Page Language="VB" %>
<script runat="server">
    Sub btnSubmit_Click(Sender As Object, E As EventArgs)
        ' Checks to see if all the
        ' controls on the page are valid!
        If Page.IsValid Then
            ' Do Something
        End If
    End Sub
</script>

<html>
<head>
<title>ASP.NET Form Validation Sample - Validation Summary</title>
</head>
<body bgcolor="#FFFFFF">

<p>
Note that this form doesn't actually do anything
except illustrate the Validators involved.
</p>

<form id="frmValidator" action="summary.aspx"
    method="post" runat="server">

    Enter Your Name:
    <asp:TextBox id="txtName" runat="server" />
    <asp:RequiredFieldValidator id="valTxtName"
        ControlToValidate="txtName"
        ErrorMessage="Please enter your name!<br />"
        runat="server">
        ***
    </asp:RequiredFieldValidator>

    <br />
    
    Enter Your Age:
    <asp:TextBox id="txtAge" runat="server" />
    <asp:RequiredFieldValidator id="valTxtAgeReq"
        ControlToValidate="txtAge"
        ErrorMessage="Please enter your age!<br />"
        Display="Dynamic"
        runat="server">
        ***
    </asp:RequiredFieldValidator>
    <asp:RangeValidator id="valTxtAgeRange"
        ControlToValidate="txtAge"
        Type="Integer"
        MinimumValue="21"
        MaximumValue="100"
        ErrorMessage="You need to be over 21 and under 100!<br />"
        Display="Dynamic"
        runat="server">
        ***
    </asp:RangeValidator>

    <br />

    <asp:button id="btnSubmit" text="Submit"
        onClick="btnSubmit_Click" runat="server" />

    <asp:ValidationSummary ID="valSummary"
        HeaderText="There was an error submitting your form.
            Please check the following:"
        DisplayMode="BulletList"
        runat="server" />
</form>


</body>
</html>

Client-Side Validation

Before I call it a wrap on this lesson, I thought I should mention a cool feature of the validation controls. They automatically perform client-side validation via javascript on higher-level browsers. The validation still takes place on the server no matter what, but you automatically get the benefit of immediate feedback on clients that support it and you don't even have to write any client-side code. Cool huh?

That's It... Get The Code

As usual here's a zip file of all the sample code mentioned in this lesson.


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES