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

  • Green city refutes a rumor sweet pastry does not turn meeting bark fleabane says the player is due professional accomplishment (2)

    Posted by ckfhrwyivq on 05/17/2013 06:24pm

    Green city refutes a rumor sweet pastry does not turn meeting bark fleabane says the player is due professional accomplishment Report from our correspondent should turn about fleabane of bark of green city header these days the message of the meeting uploads bubbling with noisely in the network, yesterday, green city club reiterates again, bark fleabane new sports season won't go. Current home turns the OK and current good player on meeting market is not much, and what like bark fleabane a such sports season can have 8 secondary attack of 8 goals is medium field player, it is difficult to do not want to make sweet bun, not long ago, fabulous Guangzhou rich force leaves with respect to Xiang Lucheng gave a high quoted price, and this also lets many green city fan have some of perturbed, bark a word of the life sighs with emotion on high small gain a few days ago, what was become to do drop out by fan is augural. "A lot of fan are on small gain @ I, have persuade to stay, still have a blessing. " meet about turning, wang Song says, the fact does not resemble outside hearsay in that way, "Before paragraph time wife gives birth to the child, now just just rejoin, restoring in what make physical ability, my where has time to be in charge of these. " of course, wang Song also says frankly, the high pay that should say rich force is not enchanted not actual also, but he expresses, one when serve as green city, should show the professional accomplishment with due player. "It is meddlesome that fan friends care green city team member, nevertheless this thing returns Wang Song is to hope everybody does not want again much Lv, club already excuse oneself from the quote of rich force. " yesterday, deputy total Bao Zhongliang tells green city club the reporter, "Wang Song is very important to green city, he and club still have two years of contracts, bilateral metropolis continues to fulfill. Bilateral metropolis continues to fulfill.. Not only Wang Song won't go, of green city brought aid to also have new [url=http://jordankicks.page4.me/]jordan sneakers for sale[/url] progress. "Of two foreign aids introduce, include Ma Zun to pull those who take a line to negotiate the way with good hold office at court develops. " Bao Zhongliang says. Wang Jiajun of our newspaper trainee Related news

    Reply
  • Shorter piece of writing illustrates the unquestionable info regarding gucci and ways in which it could impact on users.

    Posted by emeseesip on 05/07/2013 03:21am

    1 Of The Most Detailed nike Strategy guide You Ever Witnessed Or else Your Cash Back [url=http://www.guccija.biz/]gucci 財布[/url] Yo ,, incredible product. Your company got to find out more about nike right now while it's still in store ! ! [url=http://www.guccija.biz/]グッチ キーケース[/url] adidas can help everybody by simply adding a lot of exclusive features and capabilities. Its a unvaluable thing for every enthusiast of adidas. [url=http://www.guccija.biz/]グッチ 財布 新作[/url] Honest guide shows you 4 brand-new stuff over nike that nobody is speaking about. [url=http://www.chanelja.biz/]シャネル 財布[/url] How come no-one is talking about nike and something that you ought to accomplish straight away. [url=http://www.chanelja.biz/]シャネル チェーンウォレット[/url] Different questions regarding nike replied and consequently the reasons why you really should review each and every phrase on this write up. [url=http://www.chanelja.biz/]財布 chanel[/url] The basics of the nike that you could take pleasure from starting off today.[url=http://www.nikeja.biz/]nike[/url] Tips on how to comprehend every aspect there is to know related to gucci in eight basic steps.

    Reply
  • dsjdsjsdjd

    Posted by zczczc on 04/17/2013 07:03am

    asdfjadfjasdasjdfasjasjasjfasdjasd

    Reply
  • huadasdasdbd

    Posted by fcghgfhgfhgf on 04/17/2013 07:02am

    asdasdasdsadsadsadsadsadsdsad

    Reply
  • 354345354

    Posted by 54464 on 10/20/2012 11:39pm

    543543

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

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Information is data with context. The era of Big Data has begun demonstrating to information security that there is more that can, and must, be done to identify threats, reduce risk, address fraud, and improve compliance monitoring activities by bringing better context to data and thereby creating information for actionable intelligence. This analyst report sets the stage and provides insights into IT and information security practitioners' perceptions of the impediments to, and the solutions necessary for, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds