Using the RangeValidator


As we saw in the preceding section, the CompareValidator can be used to ensure that an input maintains some relation with either a constant value or the value in another user input. However, what if we wanted to ensure that an input was between a range of values? If we were to use the CompareValidator, we'd need to use two CompareValidators, one that did a GreaterThanEqual comparison on the lower bound of the range and one that did a LessThanEqual comparison on the upper bound of the range.

If the upper and lower bound of the range are constant values, we can use a single RangeValidator instead of using two CompareValidators. For the ValidationControlTestBed.aspx ASP.NET page, the age input is a suitable candidate for a RangeValidator because the input must fall within a sensible range (such as 0150).

By the Way

The RangeValidator can be used only when both the upper and lower bounds of the range are constant values. Therefore, a RangeValidator could not be used for the number of male children input because the upper bound of the range is the value the user entered in the total number of children text box.


Add a RangeValidator immediately following the age TextBox Web control, as shown in Figure 12.16.

Figure 12.16. A RangeValidator has been added to the ASP.NET page.


As with all validation controls, we need to set the ControlToValidate and ErrorMessage properties. Because we want to validate the input from the age TextBox Web control, set the ControlToValidate property to age. Set the ErrorMessage property to Age must be between 0 and 150.

The RangeValidator, like the CompareValidator, has a Type property that specifies the data type the input must be provided in. Because we want the user to enter his age as a number without decimals, set the Type property to Integer.

All that remains is to specify the upper and lower bound of the acceptable range of values for the age input. The RangeValidator's MaximumValue and MinimumValue properties specify the upper and lower bound, respectively. Because we want to enforce that the user enters an age between 0 and 150, set the MaximumValue property to 150 and the MinimumValue property to 0.

After you have set these properties, your screen should look similar to Figure 12.17.

Figure 12.17. The properties of the RangeValidator have been set.


If you take a moment to view the ValidationControlTestBed.aspx ASP.NET page through a browser, you can see that an error message is displayed unless either no input is provided into the age text box or the input provided is an integer value between 0 and 150.




Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net