ASP.NET Tutorial/Validation/RangeValidator — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:57, 26 мая 2010

asp:RangeValidator is converted to JavaScript code after loading in client side

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="MyPage" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Your age:
        <asp:TextBox ID="age" runat="server" Columns="4"></asp:TextBox>
        <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="age" ErrorMessage="Age must be between 0 and 150"
            MaximumValue="150" MinimumValue="0" Type="Integer"></asp:RangeValidator><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Click Me" />
        <asp:Label ID="results" runat="server"></asp:Label></div>
    </form>
</body>
</html>
File: Default.aspx.vb

Partial Class MyPage
    Inherits System.Web.UI.Page
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        If Page.IsValid Then
            results.Text = "Input is valid..."
        Else
            results.Text = "Input is <b>not</b> valid..."
        End If
    End Sub
End Class


Birthday range

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Simple Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <!-- Username -->
        
          Username:<br />
          <asp:TextBox id="usernameTextBox" runat="server" />
          <asp:RequiredFieldValidator id="usernameReq"
              runat="server"
              ControlToValidate="usernameTextBox"
              ErrorMessage="Username is required!"
              SetFocusOnError="True" />
        
        <!-- Password -->
        
          Password and Confirmation:<br />
          <asp:TextBox id="passwordTextBox" runat="server"
              TextMode="Password" />
          <asp:RequiredFieldValidator id="passwordReq"
              runat="server"
              ControlToValidate="passwordTextBox"
              ErrorMessage="Password is required!"
              SetFocusOnError="True" 
              Display="Dynamic" />
          <asp:TextBox id="confirmPasswordTextBox" 
                       runat="server"
                       TextMode="Password" />
          <asp:RequiredFieldValidator id="confirmPasswordReq"
              runat="server" 
              ControlToValidate="confirmPasswordTextBox"
              ErrorMessage="Password confirmation is required!"
              SetFocusOnError="True" 
              Display="Dynamic" />
          <asp:CompareValidator id="comparePasswords" runat="server"
              ControlToCompare="passwordTextBox"
              ControlToValidate="confirmPasswordTextBox"
              ErrorMessage="Your passwords do not match up!"
              Display="Dynamic" />
        
        <!-- Birth Date -->
        
          Birth Date:<br />
          <asp:TextBox id="birthDateTextBox" runat="server" />
          <asp:RangeValidator id="birthDateRangeTest" runat="server"
              Type="Date" ControlToValidate="birthDateTextBox" 
              MinimumValue="1/1/1970" 
              MaximumValue="12/31/1979"
              ErrorMessage="You must"ve been born in the 1970s!" />
        
        <!-- Submit Button -->
        
          <asp:Button id="submitButton" runat="server"
              Text="Submit" OnClick="submitButton_Click" />
        
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
    protected void submitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            submitButton.Text = "Valid";
        }
        else
        {
            submitButton.Text = "Invalid!";
        }
    }
}


Manual Validation

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ManualValidation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Manual Validation</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        A number (1 to 10):
      <asp:TextBox id="txtValidated" runat="server"></asp:TextBox>&nbsp;
      <asp:RangeValidator id="RangeValidator"  
                          runat="server" 
                          ErrorMessage="This Number Is Not In The Range" 
                          ControlToValidate="txtValidated" 
                          MaximumValue="10" 
                          MinimumValue="1" 
                          Type="Integer" 
                          EnableClientScript="False"></asp:RangeValidator><br/>
    <br />
    Not validated:
    <asp:TextBox id="txtNotValidated" runat="server"></asp:TextBox><br/>
        <br />
    <br />
    <asp:Button id="cmdOK" runat="server" Text="OK" OnClick="cmdOK_Click" Width="36px"></asp:Button><br />
    <br />
    <asp:Label id="lblMessage" runat="server" EnableViewState="False"></asp:Label>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ManualValidation : System.Web.UI.Page
{
  protected void cmdOK_Click(object sender, EventArgs e)
  {
    string errorMessage = "<b>Mistakes found:</b><br />";
    bool pageIsValid = true;
    foreach (BaseValidator ctrl in this.Validators)
    {
      if (!ctrl.IsValid)
      {
        pageIsValid = false;
        errorMessage += ctrl.ErrorMessage + "<br />";
          TextBox ctrlInput = (TextBox)this.FindControl(ctrl.ControlToValidate);
        errorMessage += " * Failed: ";
        errorMessage += ctrlInput.Text + "<br />";
      }
    }
    if (!pageIsValid) lblMessage.Text = errorMessage;
  }
}


RangeValidator checks whether the value falls between a minimum and maximum value

You must set five properties when using this control:
ControlToValidate:   The ID of the form field being validated.
Text:                The error message.
MinimumValue:        The minimum value.
MaximumValue:        The maximum value.
Type:                The type of comparison. 
                     Possible values are String, Integer, Double, Date, and Currency.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show RangeValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblAge"
        Text="Age:"
        AssociatedControlID="txtAge"
        Runat="server" />
    <asp:TextBox
        id="txtAge"
        Runat="server" />
    <asp:RangeValidator
        id="reqAge"
        ControlToValidate="txtAge"
        Text="(Invalid Age)"
        MinimumValue="5"
        MaximumValue="100"
        Type="Integer"
        Runat="server" />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>


RangeValidator for number and date

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        Enter a number between 1 and 20:<br />
        <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
        <asp:RangeValidator ID="rangeNum" runat="server" 
           ControlToValidate="txtNumber" 
           MinimumValue="1"
           MaximumValue="20"
           Type="Integer"
           SetFocusOnError="true"
           Text="Please enter number between 1 and 20" />         
    
    
    Enter a valid date from 2006:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:RangeValidator ID="rangeDate" runat="server" 
       ControlToValidate="txtDate" 
       CultureInvariantValues="true"
       MinimumValue="2006/01/01"
       MaximumValue="2006/12/31"
       Type="Date"
       SetFocusOnError="true"
       Text="Please enter a valid date from 2006" />         
       
     
      <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
      
    </div>
    </form>
</body>
</html>


Set Minimum/Maximum Value, ErrorMessage, ControlToValidate, EnableClientScript for asp:RangeValidator (C#)

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ValidationTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Validation Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    A number (1 to 10):
    <asp:TextBox id="txtValidated" runat="server"></asp:TextBox>
    <asp:RangeValidator id="RangeValidator" 
                        runat="server" 
                        ErrorMessage="This Number Is Not In The Range" 
                        ControlToValidate="txtValidated" 
                        MaximumValue="10" 
                        MinimumValue="1" 
                        Type="Integer" 
                        EnableClientScript="False"></asp:RangeValidator>&nbsp;
    Not validated:
    <asp:TextBox id="txtNotValidated" runat="server"></asp:TextBox><br />
  
   <asp:Button id="cmdOK" 
                runat="server" 
                Text="OK" 
                OnClick="cmdOK_Click" 
                Width="46px"></asp:Button><br />
    <asp:Label id="lblMessage" 
               runat="server" 
               EnableViewState="False" 
               Font-Bold="True" 
               ForeColor="Red"></asp:Label>&nbsp;
  
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ValidationTest : System.Web.UI.Page
{
  protected void cmdOK_Click(object sender, EventArgs e)
  {
    if (!Page.IsValid) return;
    lblMessage.Text = "cmdOK_Click event handler executed.";
  }
}


Use asp:RangeValidator to check the value range in an asp:textbox

<html><body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server" /><br>
      <asp:Panel id="Panel1" runat="server">
         <table>
         <tr>
            <td valign="top">City, State, ZIP (5-digit):</td>
            <td valign="top">
               <asp:TextBox id="tbCity" 
                  runat="server" />,
               <asp:TextBox id="tbState" runat="server" size=2 />&nbsp;
               <asp:TextBox id="tbZIP" runat="server" size=5 /><br>
               <asp:RegularExpressionValidator runat="server"
                  ControlToValidate="tbZIP"
                  ValidationExpression="[0-9]{5}"
                  ErrorMessage="That is not a valid ZIP" /><br>
               <asp:RangeValidator runat="server"
                  ControlToValidate="tbZIP"
                  MinimumValue="00000" 
                  MaximumValue="22222"
                  Type="String"
                  ErrorMessage="You don"t live in the correct region" />
            </td>
         </tr>
         <tr>
            <td colspan="2" valign="top" align="right">
               <asp:Button id="Submit" runat="server" 
                  text="Add" />
            </td>
         </tr>
         </table>
      </asp:Panel>
   </form>
</body></html>


Using the RangeValidator control to test an integer value

<%@ Page Language="VB" %>
<script runat="server">
    Protected Sub Button1_Click(sender As Object, e As EventArgs)
       Label1.Text = "Passwords match"
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>CompareFieldValidator</title>
</head>
<body>
    <form id="Form1" runat="server">
        Age:
        <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
          &nbsp;
        <asp:RangeValidator ID="RangeValidator1" 
                            Runat="server"
                            ControlToValidate="TextBox1" 
                            Type="Integer"
                            ErrorMessage="You must be between 30 and 40"
                            MaximumValue="40" 
                            MinimumValue="30"></asp:RangeValidator>
        
            <asp:Button ID="Button1" OnClick="Button1_Click" 
             Runat="server" Text="Login"></asp:Button>
        
        
            <asp:Label ID="Label1" Runat="server"></asp:Label>
        
    </form>
</body>
</html>


Using the RangeValidator control to test a string date value (C#)

<%@ Page Language="C#" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        RangeValidator1.MinimumValue = DateTime.Now.ToShortDateString();
        RangeValidator1.MaximumValue = DateTime.Now.AddDays(14).ToShortDateString();
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid) 
        {
            Label1.Text = "You are set to arrive on: " + TextBox1.Text.ToString();
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Date Validation Check</title>
</head>
<body>
    <form id="form1" runat="server">
        Arrival Date:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>&nbsp;
        <asp:RangeValidator ID="RangeValidator1" 
                            runat="server" 
                            ErrorMessage="select a date within the next two weeks." 
                            ControlToValidate="TextBox1" Type="Date"></asp:RangeValidator><br />
        <br />
        Select your arrival date:<br />
        <asp:Calendar ID="Calendar1" 
                      runat="server" 
                      OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
        <asp:Button ID="Button1" runat="server" Text="Button" 
         OnClick="Button1_Click" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>        
    </form>
</body>
</html>


Using the RangeValidator control to test a string date value (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        RangeValidator1.MinimumValue = DateTime.Now.ToShortDateString()
        RangeValidator1.MaximumValue = DateTime.Now.AddDays(14).ToShortDateString()
    End Sub
    
    Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, _
      ByVal e As System.EventArgs)
        TextBox1.Text = Calendar1.SelectedDate.ToShortDateString()
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs)
        If Page.IsValid Then
            Label1.Text = "You are set to arrive on: " & TextBox1.Text
        End If
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Date Validation Check</title>
</head>
<body>
    <form id="form1" runat="server">
        Arrival Date:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>&nbsp;
        <asp:RangeValidator ID="RangeValidator1" runat="server" 
                            ErrorMessage="select a date within the next two weeks." 
                            ControlToValidate="TextBox1" 
                            Type="Date"/>
        <br />
        Select your arrival date:<br />
        <asp:Calendar ID="Calendar1" 
                      runat="server" 
                      OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
        <br />
        <asp:Button ID="Button1" 
                    runat="server" 
                    Text="Button" 
                    OnClick="Button1_Click" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>        
    </form>
</body>
</html>