In
this chapter, you learn how to validate form fields when a form is
submitted to the web server. You can use the validation controls to
prevent users from submitting the wrong type of data into a database
table. For example, you can use validation controls to prevent a user
from submitting the value “Apple” for a birth date field.
In
the first part of this chapter, you are provided with an overview of
the standard validation controls included in the ASP.NET 3.5 Framework.
You learn how to control how validation errors are displayed, how to
highlight validation error messages, and how to use validation groups.
You are provided with sample code for using each of the standard
validation controls.
Next,
we extend the basic validation controls with our own custom validation
controls. For example, you learn how to create an AjaxValidator control
that enables you to call a server-side validation function from the
client.
Overview of the Validation Controls
Six validation controls are included in the ASP.NET 3.5 Framework:
RequiredFieldValidator—Enables you to require a user to enter a value in a form field.
RangeValidator—Enables you to check whether a value falls between a certain minimum and maximum value.
CompareValidator—Enables you to compare a value against another value or perform a data type check.
RegularExpressionValidator—Enables you to compare a value against a regular expression.
CustomValidator—Enables you to perform custom validation.
ValidationSummary—Enables you to display a summary of all validation errors in a page.
You
can associate the validation controls with any of the form controls
included in the ASP.NET Framework. For example, if you want to require a
user to enter a value into a TextBox control, then you can associate a
RequiredFieldValidator control with the TextBox control.
Validation Controls and JavaScript
By
default, the validation controls perform validation on both the client
(the browser) and the server. The validation controls use client-side
JavaScript. This is great from a user experience perspective because you
get immediate feedback whenever you enter an invalid value into a form
field.
NOTE
The
RequiredFieldValidator will not perform client-side validation until
after you attempt to submit a form at least once or you enter and remove
data in a form field. Client-side JavaScript is supported on any
uplevel browser. Supported browsers include Internet Explorer, Firefox,
and Opera. This is a change from the previous version of ASP.NET, which
supported only Internet Explorer as an uplevel browser.
You
can use the validation controls with browsers that do not support
JavaScript (or do not have JavaScript enabled). If a browser does not
support JavaScript, the form must be posted back to the server before a
validation error message is displayed. Even when validation happens on
the client, validation is still performed on the server. This is done
for security reasons. If someone creates a fake form and submits the
form data to your web server, the person still won’t be able to submit
invalid data.
If
you prefer, you can disable client-side validation for any of the
validation controls by assigning the value False to the validation
control’s EnableClientScript property.
Using Page.IsValid
As
mentioned earlier, you should always check the Page.IsValid property
when working with data submitted with a form that contains validation
controls. Each of the validation controls includes an IsValid property
that returns the value True when there is not a validation error. The
Page.IsValid property returns the value True when the IsValid property
for all of the validation controls in a page returns the value True.
It
is easy to forget to check the Page.IsValid property. When you use an
uplevel browser that supports JavaScript with the validation controls,
you are prevented from submitting a form back to the server when there
are validation errors. However, if someone requests a page using a
browser that does not support JavaScript, the page is submitted back to
the server even when there are validation errors.
Setting the Display Property
All
the validation controls include a Display property that determines how
the validation error message is rendered. This property accepts any of
the following three possible values:
Static
Dynamic
None
By
default, the Display property has the value Static. When the Display
property has this value, the validation error message rendered by the
validation control looks like this:
<span id=”reqProductName” style=”color:Red;visibility:hidden;”>(Required)</span>
Notice
that the error message is rendered in a <span> tag that includes a
Cascading Style Sheet style attribute that sets the visibility of the
<span> tag to hidden. If, on the other hand, you set the Display
property to the value Dynamic, the error message is rendered like this:
<span id=”reqProductName” style=”color:Red;display:none;”>(Required)</span>
In
this case, a Cascading Style Sheet display attribute hides the contents
of the <span> tag. Both the visibility and display attributes can
be used to hide text in a browser. However, text hidden with the
visibility attribute still occupies screen real estate. Text hidden with
the display attribute, on the other hand, does not occupy screen real
estate.
In
general, you should set a validation control’s Display property to the
value Dynamic. That way, if other content is displayed next to the
validation control, the content is not pushed to the right. All modern
browsers (Internet Explorer, Firefox, and Opera) support the Cascading
Style Sheet display attribute.
The
third possible value of the Display property is None. If you prefer,
you can prevent the individual validation controls from displaying an
error message and display the error messages with a ValidationSummary
control. You learn how to use the ValidationSummary control later in
this chapter.
Highlighting Validation Errors
When
a validation control displays a validation error, the control displays
the value of its Text property. Normally, you assign a simple text
string, such as ”(Required)” to the Text property. However, the Text
property accepts any HTML string.
Another
way that you can emphasize errors is to take advantage of the
SetFocusOnError property that is supported by all the validation
controls. When this property has the value True, the form focus is
automatically shifted to the control associated with the validation
control when there is a validation error.
The
Page.Validators property is used in the Page_PreRender() handler. The
IsValid property is checked for each control in the Page.Validators
collection. If IsValid returns False, then the control being validated
by the validation control is highlighted with a yellow background color.
Using Validation Groups
In
the first version of the ASP.NET Framework, there was no easy way to
add two forms to the same page. If you added more than one form to a
page, and both forms contained validation controls, then the validation
controls in both forms were evaluated regardless of which form you
submitted.
For
example, imagine that you wanted to create a page that contained both a
login and registration form. The login form appeared in the left column
and the registration form appeared in the right column. If both forms
included validation controls, then submitting the login form caused any
validation controls contained in the registration form to
be evaluated.
After
the ASP.NET 2.0 Framework, you no longer face this limitation. The
ASP.NET 2.0 Framework introduces the idea of validation groups. A
validation group enables you to group related form fields together.
The
validation controls and the button controls all include ValidationGroup
properties. The controls associated with the login form all have the
value ”LoginGroup” assigned to their ValidationGroup properties. The
controls associated with the register form all have the value
”RegisterGroup” assigned to their ValidationGroup properties. Because
the form fields are grouped into different validation groups, you can
submit the two forms independently. You can assign any string to the
ValidationGroup property. The only purpose of the string is to associate
different controls in a form together into different groups.
Disabling Validation
All
the button controls—the Button, LinkButton, and ImageButton
control—include a CausesValidation property. If you assign the value
False to this property, then clicking the button bypasses any validation
in the page. Bypassing validation is useful when creating a Cancel
button.
Using the RequiredFieldValidator Control
The
RequiredFieldValidator control enables you to require a user to enter a
value into a form field before submitting the form. You must set two
important properties when using the RequiredFieldValdiator control:
ControlToValidate—The ID of the form field being validated.
Text—The error message displayed when validation fails.
By
default, the RequiredFieldValidator checks for a nonempty string
(spaces don’t count). If you enter anything into the form field
associated with the RequiredFieldValidator, then the
RequiredFieldValidator does not display its validation error message.
You can use the RequiredFieldValidator control’s InitialValue property to specify a default value other than an empty string.
The
first list item displayed by the DropDownList control displays the text
”Select Color”. If you submit the form without selecting a color from
the DropDownList control, then a validation error message is displayed.
Notice
that the RequiredFieldValidator control includes an InitialValue
property. The value of the first list from the DropDownList control is
assigned to this property.
Using the RangeValidator Control
The
RangeValidator control enables you to check whether the value of a form
field falls between a certain minimum and maximum value. You must set
five properties when using this control:
ControlToValidate—The ID of the form field being validated.
Text—The error message displayed when validation fails.
MinimumValue—The minimum value of the validation range.
MaximumValue—The maximum value of the validation range.
Type—The type of comparison to perform. Possible values are String, Integer, Double, Date, and Currency.
The
validation message is also displayed if you enter a value that is not a
number. If the value entered into the form field cannot be converted
into the data type represented by the RangeValidator control’s Type
property, then the
error
message is displayed. If you don’t enter any value into the age field
and submit the form, no error message is displayed. If you want to
require a user to enter a value, you must associate a
RequiredFieldValidator with the form field.
Don’t
forget to set the Type property when using the RangeValidator control.
By default, the Type property has the value String, and the
RangeValidator performs a string comparison to determine whether a
values falls between the minimum and maximum value.
Using the CompareValidator Control
The
CompareValidator control enables you to perform three different types
of validation tasks. You can use the CompareValidator to perform a data
type check. In other words, you can use the control to determine whether
a user has entered the proper type of value into a form field, such as a
date in a birth date field.
You
also can use the CompareValidator to compare the value entered into a
form field against a fixed value. For example, if you are building an
auction website, you can use the CompareValidator to check whether a new
minimum bid is greater than the previous minimum bid.
Finally,
you can use the CompareValidator to compare the value of one form field
against another. For example, you use the CompareValidator to check
whether the value entered into the meeting start date is less than the
value entered into the meeting end date.
The CompareValidator has six important properties:
ControlToValidate—The ID of the form field being validated.
Text—The error message displayed when validation fails.
Type—The type of value being compared. Possible values are String, Integer, Double, Date, and Currency.
Operator—The
type of comparison to perform. Possible values are DataTypeCheck,
Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and
NotEqual.
ValueToCompare—The fixed value against which to compare.
ControlToCompare—The ID of a control against which to compare.
Just
like the RangeValidator, the CompareValidator does not display an error
if you don’t enter a value into the form field being validated. If you
want to require that a user enter a value, then you must associate a
RequiredFieldValidator control with the field.
Using the RegularExpressionValidator Control
The
RegularExpressionValidator control enables you to compare the value of a
form field against a regular expression. You can use a regular
expression to represent string patterns such as email addresses, Social
Security numbers, phone numbers, dates, currency amounts, and product
codes.
The
regular expression is assigned to the RegularExpressionValidator
control’s ValidationExpression property. It looks like this:
\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Regular expressions are not fun to read. This pattern matches a simple email address. The
\w
expression represents any non-whitespace character. Therefore, roughly,
this regular expression matches an email address that contains
non-whitespace characters, followed by an @ sign, followed by
non-whitespace characters, followed by a period, followed by more
non-whitespace characters.
Just
like the other validation controls, the RegularExpressionValidator
doesn’t validate a form field unless the form field contains a value. To
make a form field required, you must associate a RequiredFieldValidator
control with the form field.
Using the CustomValidator Control
If
none of the other validation controls perform the type of validation
that you need, you can always use the CustomValidator control. You can
associate a custom validation function with the CustomValidator control.
The CustomValidator control has three important properties:
ControlToValidate—The ID of the form field being validated.
Text—The error message displayed when validation fails.
ClientValidationFunction—The name of a client-side function used to perform client-side validation.
The CustomValidator also supports one event:
ServerValidate—This event is raised when the CustomValidator performs validation.
You associate your custom validation function with the CustomValidator control by
handling the ServerValidate event.
Using the ValidationSummary Control
The
ValidationSummary control enables you to display a list of all the
validation errors in a page in one location. This control is
particularly useful when working with large forms. If a user enters the
wrong value for a form field located toward the end of the page, then
the user might never see the error message. If you use the
ValidationSummary control, however, you can always display a list of
errors at the top of the form.
You
might have noticed that each of the validation controls includes an
ErrorMessage property. We have not been using the ErrorMessage property
to represent the validation error message. Instead, we have used the
Text property.
The
distinction between the ErrorMessage and Text property is that any
message that you assign to the ErrorMessage property appears in the
ValidationSummary control, and any message that you assign to the Text
property appears in the body of the page. Normally, you want to keep the
error message for the Text property short (for example, ”Required!”).
The message assigned to the ErrorMessage property, on the other hand,
should identify the form field that has the error (for example, ”First
name is required!”).
The ValidationSummary control supports the following properties:
DisplayMode—Enables you to specify how the error messages are formatted. Possible values are BulletList, List, and SingleParagraph.
HeaderText—Enables you to display header text above the validation summary.
ShowMessageBox—Enables you to display a popup alert box.
ShowSummary—Enables you to hide the validation summary in the page.
If
you set the ShowMessageBox property to the value True and the
ShowSummary property to the value False, then you can display the
validation summary only within a popup alert box.
Creating Custom Validation Controls
In
this final section, you learn how to create custom validation controls.
We create two custom controls. We create an AjaxValidator control. The
AjaxValidator control performs validation on the client by passing
information back to a custom function defined on the server.
You
create a new validation control by deriving a new control from the
BaseValidator class. As its name implies, the BaseValidator class is the
base class for all the validation controls, including the
RequiredFieldValidator and RegularExpressionValidator controls. The
BaseValidator class is a MustInherit (abstract) class, which requires
you to implement a single method:
EvaluateIsValid—Returns true when the form field being validated is valid.
The
BaseValidator class also includes several other methods that you can
override or otherwise use. The most useful of these methods is the
following:
GetControlValidationValue—Enables you to retrieve the value of the control being validated.
When
you create a custom validation control, you override the
EvaluateIsValid() method and, within the EvaluateIsValid() method, you
call GetControlValidationValue to get the value of the form field being
validated.
Creating an AjaxValidator Control
In
this section, we are going to create an extremely useful control named
the AjaxValidator control. Like the CustomValidator control, the
AjaxValidator control enables you to create a custom server-side
validation function. Unlike the CustomValidator control, however, the
AjaxValidator control enables you to call the custom validation function
from the browser.
The
AjaxValidator control uses AJAX (Asynchronous JavaScript and XML) to
call the server-side validation function from the client. The advantage
of using AJAX is that no postback to the server is apparent to the user.