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



About the Author

From ASP101

Articles originally posted on ASP101.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date