3.1. Requiring That Data Be Entered in a Field


You need to ensure that a user has entered data in a text box, such as a first or last name on a registration form.


Add a RequiredFieldValidator control to the .aspx file, and use the event handler of the control that completes the user’s entry for the page to verify that validation was successful.

In the .aspx file:

  1. Add a RequiredFieldValidator control for each text box in which data must be entered.

  2. Set the ControlToValidate attribute to the ID of the control to validate.

  3. Add Save and Cancel (or equivalently named) buttons.

  4. Set the Save button’s CausesValidation attribute to True to have validation performed when the button is clicked (set it to False for the Cancel button).

In the code-behind class, use the .NET language of your choice to add code to the event handler for the Save button’s click event that checks the Page.IsValid property and verifies that all validation was successful.

Figure 3-1 shows a typical user input form with fields for First Name and Last Name and several other types of information. Figure 3-2 shows the same form with validation error messages that appear when the user fails to complete the First Name and Last Name fields. Example 3-1 shows the .aspx file that implements the form, and Examples 3-2 and 3-3 show the VB and C# code-behind files needed to complete the application.

Form with required field validation output—normal

Figure 3-1. Form ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.