Getting Started
  Introduction
  What is ASP.NET?
  Language Support

ASP.NET Web Forms
  Introducing Web Forms
  Working with Server Controls
  Applying Styles to Controls
  Server Control Form Validation
  Web Forms User Controls
  Data Binding Server Controls
  Server-Side Data Access
  Data Access and Customization
  Working with Business Objects
  Authoring Custom Controls
  Web Forms Controls Reference
  Web Forms Syntax Reference

ASP.NET Web Services
  Introducing Web Services
  Writing a Simple Web Service
  Web Service Type Marshalling
  Using Data in Web Services
  Using Objects and Intrinsics
  The WebService Behavior
  HTML Pattern Matching

ASP.NET Web Applications
  Application Overview
  Using the Global.asax File
  Managing Application State
  HttpHandlers and Factories

Cache Services
  Caching Overview
  Page Output Caching
  Page Fragment Caching
  Page Data Caching

Configuration
  Configuration Overview
  Configuration File Format
  Retrieving Configuration

Deployment
  Deploying Applications
  Using the Process Model
  Handling Errors

Security
  Security Overview
  Authentication & Authorization
  Windows-based Authentication
  Forms-based Authentication
  Authorizing Users and Roles
  User Account Impersonation
  Security and WebServices

Localization
  Internationalization Overview
  Setting Culture and Encoding
  Localizing ASP.NET Applications
  Working with Resource Files

Tracing
  Tracing Overview
  Trace Logging to Page Output
  Application-level Trace Logging

Debugging
  The SDK Debugger

Performance
  Performance Overview
  Performance Tuning Tips
  Measuring Performance

ASP to ASP.NET Migration
  Migration Overview
  Syntax and Semantics
  Language Compatibility
  COM Interoperability
  Transactions

Sample Applications
  A Personalized Portal
  An E-Commerce Storefront
  A Class Browser Application
  IBuySpy.com

  Get URL for this page

Server Control Form Validation


Introduction to Validation

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 Validator1.aspx

[Run Sample] | [View Source]

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 Validator2.aspx

[Run Sample] | [View Source]


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 Validator3.aspx

[Run Sample] | [View Source]


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 <Operator> ControlToCompare ) If the expression evaluates true, the validation result is valid.

The following sample shows how to use the CompareValidator control.

 
VB Validator4.aspx

[Run Sample] | [View Source]


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 Validator5.aspx

[Run Sample] | [View Source]


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 Validator6.aspx

[Run Sample] | [View Source]

 
VB Validator7.aspx

[Run Sample] | [View Source]


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 Validator8.aspx

[Run Sample] | [View Source]


Bringing It All Together

This sample shows a typical registration form, using the variations of validation controls discussed in this topic.

 
VB Validator9.aspx

[Run Sample] | [View Source]

Section Summary

  1. Validator controls can be used to validate input on any Web Forms page.
  2. More than one control can be used on a given input field.
  3. Client-side validation may be used in addition to server validation to improve form usability.
  4. The CustomValidator control lets the user define custom validation criteria.


Copyright 2001 Microsoft Corporation. All rights reserved.