ASP.Net/Validation by Control/By Your Function

Материал из .Net Framework эксперт
Версия от 11:51, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Date validation: start, end date (C#)

<%@ Page language="c#" %>
<%@ Import Namespace="System.Drawing" %>
  <script language="c#" runat="server">
  protected void ValidateTravelData(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
  {
    args.IsValid = false;
    DateTime departDate, returnDate;
    feedbackLabel.ForeColor = Color.Red;
    try 
    {
        departDate = DateTime.Parse(flightDepartureDateTextBox.Text);
    } catch (Exception ex) 
    {
        feedbackLabel.Text = "Invalid data entry: Departure Date is invalid. " +
                             "Enter a valid date, for example:  01/20/2006";
        return;
    }
    try 
    {
        returnDate = DateTime.Parse(flightReturnDateTextBox.Text);
    } catch (Exception ex) 
    {
        feedbackLabel.Text = "Invalid data entry: Return Date is invalid. " +
                             "Enter a valid date, for example:  01/20/2006";
        return;
    }
    // Verify that the departure date is less than the
    // return date - no same day trips in this system!
    if (departDate >= returnDate)
    {
        feedbackLabel.Text = "Invalid data entry: The Departure Date must be " + 
                             "earlier than the Return Date and no same-day " + 
                             "returns for this travel package!"; 
        return;
    }
    // Verify that the departure date is not in the past or today!
    if (departDate < DateTime.Now)
    {
        feedbackLabel.Text = "Invalid data entry:  The Departure Date cannot " +
                             "be in the past or today!"; 
        return;
    }
    // Everthing is valid - set the IsValid flag...
    args.IsValid = true;
  }
   
  private void bookTheTripButton_Click(object sender, EventArgs e)
  {
    // Has the page been validated for all data entry?
    if (!(Page.IsValid))
    {
      return;
    }
    // We"re all set - book the flight!
    DateTime departDate, returnDate;
    departDate = DateTime.Parse(flightDepartureDateTextBox.Text);
    returnDate = DateTime.Parse(flightReturnDateTextBox.Text);
    feedbackLabel.ForeColor = Color.Black;
    feedbackLabel.Text = "Success!  Your trip from Chicago to London " + 
                         "will depart on the " + departDate.ToLongDateString() + 
                         " and return on the " + returnDate.ToLongDateString();
  }</script>

<html>
<head></head>
  <body>
    <h1>Travel: Chicago to London</h1>
    <form id="TravelForm" method="post" runat="server">
    <!-- Flight Info -->
      <asp:panel id="Panel" runat="server" Width="504px" Height="89px" 
      BackColor="Wheat">Departure Date:
      <asp:TextBox id="flightDepartureDateTextBox" runat="server"
      Width="80px" Height="22px"/>Return Date:
      <asp:TextBox id="flightReturnDateTextBox" runat="server"
       Width="80px" Height="22px"/></br>
      <asp:RequiredFieldValidator id="validateFlightDepartureDate" runat="server"
      ErrorMessage="Please enter a valid Departure Date.  "
      ControlToValidate="flightDepartureDateTextBox" />
      <asp:RequiredFieldValidator id="validateFlightReturnDate" runat="server"
      ErrorMessage="Please enter a valid Return Date."
      ControlToValidate="flightReturnDateTextBox" />
      <asp:CustomValidator id="validateFlightDates" runat="server"
      ControlToValidate="flightDepartureDateTextBox"
      OnServerValidate="ValidateTravelData" />
      </asp:panel>

    <p>
    <asp:Button id="bookTheTripButton" runat="server" Text="Book This Trip"
              OnClick="bookTheTripButton_Click" />
     </p>
     <p>
     <asp:Label id="feedbackLabel" runat="server" BackColor="Wheat" Font-Bold="True"
              Text="Select your options, then click the "Book This Trip" button!" />
     </p>
    </form>
  </body>
</html>



Implement custom validation control event (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
    Protected Sub valProductCode_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        If args.Value.Length = 4 Then
            args.IsValid = True
        Else
            args.IsValid = False
        End If
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Validate Empty Text</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Label  
        id="lblProductCode"
        Text="Product Code:"
        AssociatedControlID="txtProductCode"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtProductCode"
        Runat="server" />
    <asp:CustomValidator
        id="valProductCode"
        ControlToValidate="txtProductCode"
        Text="(Invalid product code)"
        ValidateEmptyText="true"
        OnServerValidate="valProductCode_ServerValidate" 
        Runat="server" />
    
    <br /><br />
    
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />    
    
    </div>
    </form>
</body>
</html>



Validate by a Server Validate function (VB.net)

<%@ Page Language=VB Debug=true %>
<script runat=server>
Sub Answer_ServerValidation(source As object, E As ServerValidateEventArgs)
    If E.Value = "VB" or E.Value = "VB.NET" or E.Value = "C#" _
        or E.Value = "C#.NET" or E.Value = "A bunch of others." Then
        E.IsValid = True
    Else
        E.IsValid = False
    End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Using a RegularExpressionValidator Control to Test a Zip Code</TITLE>
</HEAD>
<form runat="server">
<BR><BR>
What languages can you use with ASP.NET?<BR>
<asp:textbox 
    id="txtAnswer" 
    runat=server 
/>
<asp:customvalidator 
    id="custom9"
    controltovalidate="txtAnswer"
    OnServerValidate="Answer_ServerValidation"
    display="Dynamic"
    font-name="Verdana"
    font-bold="True"
    font-size="10pt"
    runat="server">
    <BR>Incorrect answer please try again!
</asp:CustomValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    type="Submit"
    runat="server"
/>
</form>
</BODY>
</HTML>



Validate control in code behind in C#

<%@ Page language="c#" src="CustomerForm.aspx.cs" AutoEventWireup="false" Inherits="CustomerForm" %>
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      <DIV style="BORDER-RIGHT: thin groove; BORDER-TOP: thin groove; FONT-SIZE: x-small; Z-INDEX: 101; LEFT: 16px; BORDER-LEFT: thin groove; WIDTH: 613px; BORDER-BOTTOM: thin groove; FONT-FAMILY: Verdana; POSITION: absolute; TOP: 20px; HEIGHT: 364px; BACKGROUND-COLOR: lightyellow"
        ms_positioning="GridLayout">
        <asp:TextBox id="txtUserName" style="Z-INDEX: 101; LEFT: 160px; POSITION: absolute; TOP: 16px"
          runat="server" Width="152px"></asp:TextBox>
        <asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 72px; POSITION: absolute; TOP: 19px" runat="server"
          Font-Bold="True">User Name:</asp:Label>
        <asp:TextBox id="txtPassword" style="Z-INDEX: 103; LEFT: 160px; POSITION: absolute; TOP: 56px"
          runat="server" TextMode="Password" Width="152px"></asp:TextBox>
        <asp:Label id="Label2" style="Z-INDEX: 104; LEFT: 80px; POSITION: absolute; TOP: 59px" runat="server"
          Font-Bold="True">Password:</asp:Label>
        <asp:TextBox id="txtRetype" style="Z-INDEX: 105; LEFT: 160px; POSITION: absolute; TOP: 88px"
          runat="server" TextMode="Password" Width="152px"></asp:TextBox>
        <asp:Label id="Label3" style="Z-INDEX: 106; LEFT: 13px; POSITION: absolute; TOP: 91px" runat="server"
          Font-Bold="True">Password (retype):</asp:Label>
        <asp:Label id="Label4" style="Z-INDEX: 107; LEFT: 104px; POSITION: absolute; TOP: 140px" runat="server"
          Font-Bold="True">E-mail:</asp:Label>
        <asp:TextBox id="txtEmail" style="Z-INDEX: 108; LEFT: 160px; POSITION: absolute; TOP: 136px"
          runat="server" Width="152px"></asp:TextBox>
        <asp:TextBox id="txtAge" style="Z-INDEX: 109; LEFT: 160px; POSITION: absolute; TOP: 176px" runat="server"
          Width="152px"></asp:TextBox>
        <asp:Label id="Label5" style="Z-INDEX: 110; LEFT: 117px; POSITION: absolute; TOP: 179px" runat="server"
          Width="32px" Height="16px" Font-Bold="True">Age:</asp:Label>
        <asp:Label id="Label6" style="Z-INDEX: 111; LEFT: 48px; POSITION: absolute; TOP: 228px" runat="server"
          Width="106px" Height="24px" Font-Bold="True">Referrer Code:</asp:Label>
        <asp:TextBox id="txtCode" style="Z-INDEX: 112; LEFT: 160px; POSITION: absolute; TOP: 224px" runat="server"
          Width="152px"></asp:TextBox>
        <asp:RequiredFieldValidator id="vldUserName" style="Z-INDEX: 113; LEFT: 336px; POSITION: absolute; TOP: 18px"
          runat="server" ErrorMessage="You must enter a user name." ControlToValidate="txtUserName"></asp:RequiredFieldValidator>
        <asp:RequiredFieldValidator id="vldPassword" style="Z-INDEX: 115; LEFT: 336px; POSITION: absolute; TOP: 59px"
          runat="server" ErrorMessage="You must enter a password." ControlToValidate="txtPassword"></asp:RequiredFieldValidator>
        <asp:CompareValidator id="vldRetype" style="Z-INDEX: 114; LEFT: 336px; POSITION: absolute; TOP: 93px"
          runat="server" ErrorMessage="Your password does not match." ControlToCompare="txtPassword" ControlToValidate="txtRetype"></asp:CompareValidator>
        <asp:RegularExpressionValidator id="vldEmail" style="Z-INDEX: 117; LEFT: 337px; POSITION: absolute; TOP: 139px"
          runat="server" ErrorMessage="This email is missing the @ symbol." ValidationExpression=".+@.+" ControlToValidate="txtEmail"></asp:RegularExpressionValidator>
        <asp:RangeValidator id="vldAge" style="Z-INDEX: 116; LEFT: 337px; POSITION: absolute; TOP: 180px" runat="server"
          ErrorMessage="This age is not between 0 and 120." Type="Integer" MaximumValue="120" MinimumValue="0"
          ControlToValidate="txtAge"></asp:RangeValidator>
        <asp:CustomValidator id="vldCode" style="Z-INDEX: 118; LEFT: 337px; POSITION: absolute; TOP: 227px" runat="server"
          ErrorMessage="Try a string that starts with 014." ControlToValidate="txtCode" ClientValidationFunction="MyCustomValidation"></asp:CustomValidator>
        <asp:Button id="cmdSubmit" style="Z-INDEX: 119; LEFT: 160px; POSITION: absolute; TOP: 304px"
          runat="server" Width="120px" Text="Submit"></asp:Button>
        <asp:Button id="cmdCancel" style="Z-INDEX: 120; LEFT: 304px; POSITION: absolute; TOP: 304px"
          runat="server" Width="121px" Height="24px" Text="Cancel" CausesValidation="False"></asp:Button></DIV>
      <asp:Label id="lblMessage" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 388px"
        runat="server" Width="616px" Height="72px"></asp:Label>
    </form>
  </body>
</HTML>

<%-- CustomerForm.aspx.cs
using System;
using System.Collections;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
  public class CustomerForm : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.TextBox txtUserName;
    protected System.Web.UI.WebControls.Label Label1;
    protected System.Web.UI.WebControls.TextBox txtPassword;
    protected System.Web.UI.WebControls.Label Label2;
    protected System.Web.UI.WebControls.TextBox txtRetype;
    protected System.Web.UI.WebControls.Label Label3;
    protected System.Web.UI.WebControls.Label Label4;
    protected System.Web.UI.WebControls.TextBox txtEmail;
    protected System.Web.UI.WebControls.TextBox txtAge;
    protected System.Web.UI.WebControls.Label Label5;
    protected System.Web.UI.WebControls.Label Label6;
    protected System.Web.UI.WebControls.TextBox txtCode;
    protected System.Web.UI.WebControls.RequiredFieldValidator vldUserName;
    protected System.Web.UI.WebControls.RequiredFieldValidator vldPassword;
    protected System.Web.UI.WebControls.rupareValidator vldRetype;
    protected System.Web.UI.WebControls.RegularExpressionValidator vldEmail;
    protected System.Web.UI.WebControls.RangeValidator vldAge;
    protected System.Web.UI.WebControls.CustomValidator vldCode;
    protected System.Web.UI.WebControls.Button cmdSubmit;
    protected System.Web.UI.WebControls.Button cmdCancel;
    protected System.Web.UI.WebControls.Label lblMessage;
  
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.vldCode.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(this.vldCode_ServerValidate);
      this.cmdSubmit.Click += new System.EventHandler(this.cmdSubmit_Click);
      this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void cmdSubmit_Click(object sender, System.EventArgs e)
    {
      if (!this.IsValid) return;
      lblMessage.Text = "This is a valid form.";
    }
    private void cmdCancel_Click(object sender, System.EventArgs e)
    {
        lblMessage.Text = "No attempt was made to validate this form.";
    }
    private void vldCode_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs e)
    {
      try{
        int val = Int32.Parse(e.Value.Substring(0, 3));
        if (val % 3 == 0){
          e.IsValid = true;
        }else{
          e.IsValid = false;
        }
      }catch{
        e.IsValid = false;
      }
    }
  }

--%>



Validate control manually in C#

<%@ Page language="c#" src="ManualValidation.aspx.cs" AutoEventWireup="false" Inherits="ManualValidation" %>
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      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>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Not validated:&nbsp;
      <asp:TextBox id="txtNotValidated" runat="server"></asp:TextBox><BR>
      <BR>
      <asp:Button id="cmdOK" runat="server" Text="OK"></asp:Button><BR>
      <BR>
      <asp:Label id="lblMessage" runat="server" EnableViewState="False"></asp:Label>
    </form>
  </body>
</HTML>
<%--
using System;
using System.Collections;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
  public class ManualValidation : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.TextBox txtValidated;
    protected System.Web.UI.WebControls.RangeValidator RangeValidator;
    protected System.Web.UI.WebControls.TextBox txtNotValidated;
    protected System.Web.UI.WebControls.Button cmdOK;
    protected System.Web.UI.WebControls.Label lblMessage;
  
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void cmdOK_Click(object sender, System.EventArgs e)
    {
      string errorMessage = "<b>Mistakes found:</b><br>";
      TextBox ctrlInput;
      bool pageIsValid = true;
      foreach (BaseValidator ctrl in this.Validators)
      {
        
        if (!ctrl.IsValid)
        {
          pageIsValid = false;
          errorMessage += ctrl.ErrorMessage + "<br>";
          ctrlInput = (TextBox)this.FindControl(ctrl.ControlToValidate);
          errorMessage += " * Problem is with this input: ";
          errorMessage += ctrlInput.Text + "<br>";
        }
      }
      if (!pageIsValid) lblMessage.Text = errorMessage;
      
    }
  }

--%>



Validating a Percentage Using the CustomValidator Control (VB.net)

<%@ Page Language=VB Debug=true %>
<script runat=server>
Sub Answer_ServerValidation(source As object, E As ServerValidateEventArgs)
    Dim TheNumber as Single
    If Right(E.Value, 1) = "%" Then
        TheNumber = Left(E.Value, Len(E.Value) - 1)
        If TheNumber > 100 or TheNumber < 0 Then
            E.IsValid = False
        Else
            E.IsValid = True
        End If   
    Else
        E.IsValid = False
    End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Validating a Percentage Using the CustomValidator Control</TITLE>
</HEAD>
<form runat="server">
<BR><BR>
Enter a Percentage up to 100%:<BR>
<asp:textbox 
    id="txtAnswer" 
    runat=server 
/>
<asp:customvalidator 
    id="custom9"
    controltovalidate="txtAnswer"
    OnServerValidate="Answer_ServerValidation"
    display="Dynamic"
    font-name="Verdana"
    font-bold="True"
    font-size="10pt"
    runat="server">
    <BR>Incorrect answer please try again!
</asp:CustomValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    type="Submit"
    runat="server"
/>
</form>
</BODY>
</HTML>