3.2. Requiring Data to Be in a Range


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.


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 ControlToValidate attribute to the ID of the control to validate.

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

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

  5. 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 3.1 for details.)

Figure 3-3 shows the user input form introduced in Recipe 3.1 with normal, error-free output. Figure 3-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. ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.