2.2. Requiring Data to Be In a Range

Problem

You need to ensure data entered by a user is within a defined range—for example, between two numbers, currency values, dates, or alphabetic characters.

Solution

Add a RangeValidator control to the .aspx file for each TextBox control to be checked, set the minimum and maximum acceptable values for the range, and verify that validation was successful from within the event handler of the control that completes the user’s entry for the page.

In the .aspx file:

  1. Add a RangeValidator control for each text box in which the user must enter data within a specified range.

  2. Set the control’s MinimumValue and MaximumValue attributes to the minimum and maximum values for the valid range.

  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 for the page, use the .NET language of your choice to add code to the event handler for the Save button’s click event to check the Page.IsValid property and verify that all validation was successful. (See Recipe 2.1 for details.)

Figure 2-3 shows the user input form introduced in Recipe 2.1 with normal, error-free output. Figure 2-4 shows the same form with the error message that appears on the form when the data entered into the Age field falls outside a predetermined range. Example 2-4 shows the .aspx file that implements the form, and Example ...

Get ASP.NET Cookbook 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.