JavaScript Editor Javascript validator     Javascripts

Main Page


Previous Section Next Section

8.4 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" %>
<HTML>
  <HEAD>
    <meta name=vs_targetSchema content="Internet Explorer 5.0">
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form method="post" runat="server">
    <table>
      <tr>
         <td colspan="2">
            <h5>Enter a number between 10 and 20:</h5>
         </td>
      </tr>
      <tr>
         <td>
            <asp:TextBox  Width="30" ID="txtValue" Runat="server"/>
         </td>
         <td>
            <asp:RangeValidator ID="rangeValid" 
            runat="server"
            type= "Integer"
            ControlToValidate="txtValue"
            MinimumValue="10"
            MaximumValue="20">Between 10 and 20 please</asp:RangeValidator>
         </td>
      </tr>
      <tr>
         <td colspan="2">
            <asp:Button Runat="server" Text="Validate" 
              id=Button1></asp:Button>
         </td>
      </tr>
      <tr>
         <td>
            <asp:Label ID="lblMsg" Text="" runat="server"/>
         </td>
      </tr>
    </table>
    </form>
  </body>
</HTML>
    Previous Section Next Section


    JavaScript Editor Javascript validator     Javascripts 
    Bitcoin Gambling - The Original Crypto Dice Game
    ©
    
    ©©





    ©