
|  | Validation Controls |
|  | New Features in ASP.NET 2.0 |
|
Validating Form Input Controls
What's New in 2.0
- Validation Groups - You can assign a group name to a set of validators to ensure that validation occurs only for controls in the specified group. This enables you to have multiple separately-validated forms on a single page.
- Set Focus on Error - Using the new Focus API feature in ASP.NET validators can be configured to set focus to their associated control to be validated when a validation error occurs. The first control in the form that has a validation error will receive default focus when the form is submitted.
- Culture Invariant Values - When doing conversion on a compare validator's non strongly-typed properties (CompareValidator.ValueToCompare, RangeValidator.MaximumValue, RangeValidator.MinimumValue) the validator will use a culture neutral format (Date: YYYY/MM/DD, Double & Currency: US culture format) to do the conversion when CultureInvariantValues is true.
- Validate Empty Text - The ValidateEmptyText property fixes an issue with CustomValidator. In ASP.NET 1.0 custom validation would not fire if ValidationText was empty. You can set this property to true to cause custom validation to occur for empty input values.
This section discusses these and other features of validation in ASP.NET 2.0.
The Web Forms framework includes a set of validation server controls that provide an easy-to-use but powerful way
to check input forms for errors and, if necessary, display messages to the user.
Validation controls are added to a Web Forms page like other server controls. There are controls for specific types of
validation, such as range checking or pattern matching, plus a RequiredFieldValidator that ensures that a user does
not skip an entry field. You can attach more than one validation control to an input control. For example, you
might specify both that an entry is required and that it must contain a specific range of values.
Validation controls work with a limited subset of HTML and Web server controls. For each control, a specific
property contains the value to be validated. The following table lists the input controls that may be validated.
Control |
Validation Property |
HtmlInputText |
Value |
HtmlTextArea |
Value |
HtmlSelect |
Value |
HtmlInputFile |
Value |
TextBox |
Text |
ListBox |
SelectedItem.Value |
DropDownList |
SelectedItem.Value |
RadioButtonList |
SelectedItem.Value |
Types of Validation Controls
The simplest form of validation is a required field. If the user enters any value in a field, it is valid.
If all of the fields in the page are valid, the page is valid. The following example illustrates this using the RequiredFieldValidator.
VB RequiredFieldValidator
There are also validation controls for specific types of validation, such as range checking or pattern matching. The following table lists the validation controls.
Control Name |
Description |
RequiredFieldValidator |
Ensures that the user does not skip an entry. |
CompareValidator |
Compares a user's entry with a constant value or a property value of another control using a comparison operator (less than, equal to, greater than, and so on). |
RangeValidator |
Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, or dates. Boundaries can be expressed as constants. |
RegularExpressionValidator |
Checks that the entry matches a pattern defined by a regular expression. This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on. |
CustomValidator |
Checks the user's entry using validation logic that you code yourself. This type of validation allows you to check for values derived at run time. |
ValidationSummary |
Displays the validation errors in summary form for all of the validators on a page. |
Client-Side Validation
The validation controls always perform validation checking in server code. However, if the user is working
with a browser that supports DHTML, the validation controls can also perform validation using client script.
With client-side validation, any errors are detected on the client when the form is submitted to the server.
If any of the validators are found to be in error, the submission of the form to the server is cancelled and
the validator's Text property is displayed. This permits the user to correct the input before
submitting the form to the server. Field values are revalidated as soon as the field containing the error
loses focus, thus providing the user with a rich, interactive validation experience.
Note that the Web Forms page framework always performs validation on the server, even if the validation has
already been performed on the client. This helps prevent users from being able to bypass validation by
impersonating another user or a preapproved transaction.
Client-side validation is enabled by default. If the client is capable, uplevel validation will be performed automatically.
To disable client-side validation, set the page's ClientTarget property to "Downlevel" ("Uplevel" forces client-side validation).
VB Client-side Validation
Displaying Validation Errors
When the user's input is processed (for example, when the form is submitted), the Web Forms page framework passes
the user's entry to the associated validation control or controls. The validation controls test the user's input
and set a property to indicate whether the entry passed the validation test. After all validation controls have
been processed, the IsValid property on the page is set; if any of the controls shows
that a validation check failed, the entire page is set to invalid.
If a validation control is in error, an error message may be displayed in the page by that validation control or
in a ValidationSummary control elsewhere on the page. The ValidationSummary control is displayed
when the IsValid property of the page is false. It polls each of the validation controls on the page and
aggregates the text messages exposed by each. The following example illustrates displaying errors with
a ValidationSummary control.
VB Validation Summary
Working with CompareValidator
The CompareValidator server control compares the values of two controls. CompareValidator uses three key properties to perform its validation. ControlToValidate and ControlToCompare
contain the values to compare. Operator defines the type of comparison to perform--for example, Equal or Not
Equal. CompareValidator performs the validation by evaluating these properties as an expression, as follows:
( ControlToValidate ControlToCompare )
If the expression evaluates true, the validation result is valid.
The CompareValidator server control could also be used to do Datatype validation.For example, if birth date
information has to be collected from a user registration page, CompareValidator control could be used to make
sure that the date is in a recognized format before it is submitted to the database.
The following sample shows how to use the CompareValidator control.
VB CompareValidator
Working with RangeValidator
The RangeValidator server control tests whether an input value falls within a given range.
RangeValidator uses three key properties to perform its validation. ControlToValidate contains the value
to validate. MinimumValue and MaximumValue define the minimum and maximum values of the valid
range.
This sample shows how to use the RangeValidator control.
VB RangeValidator
Working with Regular Expressions
The RegularExpressionValidator server control checks that the entry matches a pattern defined by a
regular expression. This type of validation allows you to check for predictable sequences of characters,
such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on.
RegularExpressionValidator uses two key properties to perform its validation. ControlToValidate contains
the value to validate. ValidationExpression contains the regular expression to match.
These samples illustrates using the RegularExpressionValidator control.
VB RegularExpressionValidator
VB RegularExpressionValidator 2
Performing Custom Validation
The CustomValidator server control calls a user-defined function to perform validations that the standard
validators can't handle. The custom function can execute on the server or in client-side script, such as JScript or VBScript.
For client-side custom validation, the name of the custom function must be identified in the ClientValidationFunction
property. The custom function must have the form
function myvalidator(source, arguments) .
Note that source is the client-side CustomValidator object, and arguments is an object with two properties,
Value and IsValid. The Value property is the value to be validated and the IsValid property is a
Boolean used to set the return result of the validation.
For server-side custom validation, place your custom validation in the validator's OnServerValidate
delegate.
The following sample shows how to use the CustomValidator control.
VB Custom Validator
ValidateEmptyText New in 2.0
The ValidateEmptyText property, new in ASP.NET 2.0, fixes an issue with CustomValidator. In ASP.NET 1.0 custom validation would not fire if ValidationText was empty.
You can set this property to true to cause custom validation to occur for empty input values.
Validation Groups New in 2.0
The ValidationGroup property is used when want to perform separate validation scenarios on the same page.
Set the group name on validator controls and on the button that causes validation.
This is useful with Wizard control, MultiView or data controls (editing).
By default all validators are in the "" group (default group), for back compat.
Page also exposes GetValidators("group") method and Validate("group") method.
Page.IsValid reflects validity of all controls (cumulative) that have had Validate called.
VB Validation Groups
SetFocusOnError New in 2.0
Another new validation feature in ASP.NET 2.0 is SetFocusOnError which is set on validator controls which causes the first invalid control to receive focus.
For more information about SetFocusOnError, refer to the Focus API topic in the Tips and Tricks section.
A Typical Validation Form
This sample shows a typical registration form, using the variations of validation controls discussed in this topic.
VB Validation Form
|