19.3. Ensuring That a Value Is within a Range

The RangeValidator control ensures that the user enters a value that falls within the set minimum and maximum. For example, in an online ordering page, you wouldn't allow negative values, such as −10 or ridiculous quantities such as 2 million. Follow these steps to check for a range of numbers:

  1. Add a TextBox control and a Button control to an ASP.NET page.

  2. From the Validation category of the Toolbox, drop a RangeValidator control on the page.

  3. Set the RangeValidator control's MaximumValue property to 10000 and the MinimumValue property to 1.

  4. Set the ControlToValidate property to the text box you added (for example, TextBox1).

  5. Set the Type property to Integer.

    This ensures that the control validates the input as a number, not a string.

If you enter a number outside the range of 1 to 10000, the validator complains. Likewise, if you enter Four, the validation fails.

Here's the markup generated by the preceding steps.

<asp:RangeValidator ID="RangeValidator1"
 runat="server" ControlToValidate="TextBox1"
 Display="Dynamic"
 MaximumValue="10000" MinimumValue="1"
 ErrorMessage="Must be 0 to 10000"
 SetFocusOnError="True">
</asp:RangeValidator>

Although the RangeValidator handles ranges of dates, be careful about the date format. The value 11/12/2008 means November 12 or December 11, depending on the culture. For best results, have the user select a date from a calendar control. An excellent AJAX calendar can be found in the ASP.NET Control Toolkit (see ...

Get ASP.NET 3.5 For Dummies® 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.