Many web applications involve user
input. The sad fact is, however, that users make mistakes: they skip required fields,
they put in six-digit phone numbers, and they return all manner of incorrectly formatted
data to your application. Your database routines can choke on corrupted
data, and orders can be lost. An incorrectly entered credit card number or omitted
address may result in a missed sales opportunity. Fortunately, you can write code
that checks the user’s input before it gets anywhere near your database code, or anything
else dangerous. The process of verifying the user’s input is called validation.
Traditionally, it takes a great deal of time and effort to write reliable validation code.
You need to check each field and create routines for ensuring data integrity. If bad
data is found, you need to display an error message so the user knows there is a
problem and how to correct it.
In any given application, you may choose to verify that the data is formatted correctly,
or that the values fall within a given range, or that certain fields have a value at
all. For example, if you’re processing an order, you may need to ensure that the user
has input an address and phone number, that the phone number has the right number
of digits (and no letters), and that the Social Security number entered is in the
appropriate form of nine digits separated by hyphens.
Some applications require more complex validation, in which you validate that one
field is within a range established by two other fields. For example, you might ask in
one field what date the customer wishes to arrive at your hotel, and in a second field
you might ask for the departure date. When the user books a dinner reservation,
you’ll want to ensure that the date the user chooses is between the arrival and departure
dates.
There is no limit to the complexity of the validation routines you may need to write.
Credit cards have checksums built into their values, as do ISBN numbers. Zip and
postal codes follow complex patterns, as do international phone numbers. You may
need to validate passwords, membership numbers, dollar amounts, dates, runway
choices, or launch codes.
In addition, you usually want all of this validation to happen client side so you can
avoid the delay of repeated round trips (postbacks) to the server while the user is
tinkering with his input. In the past, this was solved by writing client-side JavaScript
to validate the input, and then writing server-side script to handle input from browsers
that don’t support client-side programming. In addition, as a security check, you
may want to do server-side validation even though you have validation implemented
in the browser, as users can circumvent client-side validation code by creating a malicious
page that masquerades as a legitimate page (a tactic known as spoofing). Typically,
these security measures involved writing your validation code twice, once for
the client and once for the server.
As you can see, in traditional web programming, validation requires extensive custom
programming. The ASP.NET framework simplifies this process by providing rich controls
for validating user input. In addition to checking the validity of the data entered,
the validation controls allow you to specify how and where error messages will be displayed:
either inline with the input controls, aggregated in a summary report, or both.
You can use these controls to validate input for HTML and ASP.NET server controls.
Validation Controls
You add validation controls to your ASP.NET document as you would add any other
control. As a property of the validation control, you specify which other control you’re
validating. You may freely combine the various validation controls, and you may even
write your own custom validation controls.
With current browsers that support DHTML, .NET validation is done on the client
side, avoiding the necessity of a round trip to the server. (This client-side validation
uses JavaScript but is not part of the AJAX library.) With older browsers, your code
is unchanged, but the code sent to the client ensures validation at the server.
Validation occurs whenever the page tries to post back to the server. Sometimes you
don’t want any validation to occur, such as when a Cancel button is clicked. To prevent
validation in these circumstances, many postback controls—such as Button,
ImageButton, LinkButton, ListControl, and TextBox—have a CausesValidation property,
which you can set to dictate whether validation is performed on the page when
the control’s default event is raised.
If CausesValidation is set to true, the default value—the postback—will not occur if
any control on the page fails validation. This is a big deal, because it means the page
will not post to the server unless all of the controls on the page are in a valid state. If
CausesValidation is set to false, however, no validation will occur when that button
is used to post the page.
Sometimes you need a postback to be allowed to proceed even if some controls on
the page are invalid. For example, suppose you have a page that gathers both address
and tax information. A button on the page processes the address fields, which might
be before the user has entered some unrelated tax information. However, if a
required tax field is missing, the page will not post.
You solve this problem by using the ValidationGroup property. You can group a
bunch of validation controls together with the control (or controls) that causes the
postback so that only validation controls that are members of the group will be
applied. In this example, you can require that all the address controls are valid before
allowing the Address button to post, but allow the post even if some tax fields are
invalid.
ASP.NET includes the following validation controls:
RequiredFieldValidator
Ensures the user does not leave the field blank and skip over your input control.
A RequiredFieldValidator can be tied to a text box, which means that
the page will only pass validation if the user enters something into the text
box. With selection controls, such as a drop-down or radio buttons, the
RequiredFieldValidator ensures the user makes a selection other than the default
value you specify. The RequiredFieldValidator does not examine the validity of
the data; it only ensures that some data is entered or chosen.
RangeValidator
Ensures that the value entered is within a specified lower and upper boundary.
You can specify the range to be within a pair of numbers (such as greater than 10
and less than 100), a pair of characters (greater than D and less than K), or a pair
of dates (after 1/1/08 and before 2/28/08).
CompareValidator
Compares the user’s entry against another value. It can compare against a constant
you specify at design time, or against a property value of another control. It
can also compare against a database value.
RegularExpressionValidator
One of the most powerful validators, it compares the user’s entry with a regular
expression you provide. Regular expressions are a powerful way to match a pattern
of letters, numbers, or symbols. You can
use this validator to check for valid Social Security numbers, phone numbers,
password strength, and so forth.
CustomValidator
If none of these controls meets your needs, you can create your own using the
CustomValidator. This checks the user’s entry against whatever algorithm you
provide in a custom method.