Range Checking

At times you’ll want to validate that a user’s entry falls within a range. That range can be within a pair of numbers, characters, or dates. In addition, you can express the boundaries for the range by using constants or by comparing its value with values found in other controls.

In this simple example, you’ll prompt the user for a number between 10 and 20 and then validate his answer to ensure that it was entered properly. To do so, create a form with a prompt, a text box, and of course a RangeValidator control. The RangeValidator takes a number of attributes to designate the object to validate and the range within which its values must lie, as shown in the following HTML source:

<asp:RangeValidator ID="rangeValid" 
runat="server"
type="Integer"
ControlToValidate="txtValue"
MinimumValue="10"
MaximumValue="20">Between 10 and 20 please</asp:RangeValidator>

The text Between 10 and 20 please will be displayed if the value is not within the range of values specified by the MinimumValue and MaximumValue attributes. The type attribute designates how the value should be evaluated, and may be any of the following types: Currency, Date, Double, Integer, String.

If there are no validation errors, the form can be submitted; otherwise, the range checking error message is displayed.

The complete .aspx source is shown in Example 8-5.

Example 8-5. Range validation

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="RangeValidation.WebForm1" %> ...

Get Programming ASP.NET, Second Edition 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.