ASP.NET RangeValidator Control: Ensuring User Input Within a Specified Range

Learn how to use the ASP.NET RangeValidator control to validate user input and ensure it falls within a defined range. This tutorial explains key properties, provides code examples, and demonstrates how to implement server-side validation for various data types.



ASP.NET RangeValidator Control

Introduction to the RangeValidator Control

The RangeValidator control in ASP.NET is used to validate user input, ensuring that the value falls within a specified range. This is a server-side validation control, meaning the validation happens on the server after the user submits the form. The RangeValidator can be used to validate various data types (numbers, dates, strings). If the input control is empty, no validation is performed.

Key Properties of the RangeValidator Control

The RangeValidator control has several important properties:

Property Description
AccessKey Sets a keyboard shortcut for the control.
TabIndex Specifies the tab order.
BackColor Sets the background color.
BorderColor Sets the border color.
BorderWidth Sets the border width.
Font Sets the font style for the control's text.
ForeColor Sets the text color.
Text Sets the text displayed by the control.
ToolTip Text displayed when the mouse hovers over the control.
Visible Controls whether the control is visible.
Height Sets the height of the control.
Width Sets the width of the control.
ControlToValidate Specifies the ID of the control to validate.
ErrorMessage The message displayed if validation fails.
Type Specifies the data type (Integer, Double, Date, String).
MaximumValue The upper bound of the allowed range.
MinimumValue The lower bound of the allowed range.

Example: Using the RangeValidator

This example demonstrates using a RangeValidator to ensure that user input is within the range of 100 to 200.

ASPX Code (RangeValidator.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RangeValidator.aspx.cs" Inherits="asp.netexample.RangeValidator" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1"
    ErrorMessage="Value must be between 100 and 200" MaximumValue="200" MinimumValue="100"
    Type="Integer"></asp:RangeValidator>
<asp:Button ID="Button1" runat="server" Text="Submit" />
Output (Validation Error)

(A screenshot showing the error message displayed when the user enters a value outside the specified range would be included here.)