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:
Add a
RangeValidatorcontrol for each text box in which the user must enter data within a specified range.Set the control’s
MinimumValueandMaximumValueattributes to the minimum and maximum values for the valid range.Add Save and Cancel (or equivalently named) buttons.
Set the Save button’s
CausesValidationattribute toTrueto have validation performed when the button is clicked (set it toFalsefor 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access