ASP.NET validation controls (also known as
validators) greatly
simplify
the task of ensuring that data is entered correctly on forms. For
most validations, no code is required in either the
.aspx
file or the code-behind class. You simply
add a validator to the .aspx
file, have it
reference an input control (a server control) elsewhere on the page,
and set one or more of its validation attributes (such as
MinimumValue
or MaximumValue
,
which specify the minimum and maximum values of a validation range).
ASP.NET does all the rest. You can also combine validators to provide
multiple validations on a single input, such as a
RequiredFieldValidator
and a
RangeValidator
, which perform as their names
imply.
Validation can be performed on
the client and the server. By
default, validators perform their validation automatically on
postback
in server code. However, if the user has
a browser that supports DHTML and client-side validation is enabled,
validators can also perform their validation using client script.
Client-side validation is handy whenever you want to avoid a round
trip to the server for server-side validation, such as when you want
to make sure an entry is provided in a text box. Regardless of
whether client-side validation is performed, server-side validation
is always a good idea, if only to ensure that validation always takes
place, even when the user’s browser
doesn’t support DHTML.
This chapter includes a useful collection of recipes for validating data, starting with automatic, attribute-oriented validation and ending with custom validation. When you perform custom validation, you actually intercept an input control’s validation call and provide your own validation logic (by adding your own custom JavaScript and server-side code). Custom validation is the focus of the final two recipes of the chapter, which show you how to require a user to make a selection from a drop-down list and how to require valid user input data, such as a password that matches an entry in a database.