ASP.NET Tutorial/Validation/CustomValidator

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

Create user control based on CustomValidator

<%@ Page Language="VB" %>
<%@ Register TagPrefix="nfexASP" TagName="LoginForm" src="Control.ascx" %>
<html><body>
   <form runat="server">
      <nfexASP:LoginForm id="LoginForm1" runat="server"/>
   </form>
   
   <asp:Label id="lblMessage" runat="server" />
</body></html>

File: Control.ascx
<script runat="server">
   sub Submit(Sender as Object, e as EventArgs)
      if Page.IsValid then
         "do something
      end if
   end sub
   sub ValidateThis(Sender as Object, args as _
   ServerValidateEventArgs) 
      if len(args.Value) < 4 then
         args.IsValid = false
      else
         args.IsValid = true
      end if
   end sub
</script>
      <asp:Label id="lblMessage" runat="server" />
      <table>
      <tr>
         <td valign="top">Username:</td>
       <td valign="top">
            <asp:Textbox id="tbUserName" runat="server"/><br>
            <asp:CustomValidator runat="server"
               OnServerValidate="ValidateThis" 
               OnClientValiate="validateLength" 
               Display="Dynamic"
               ControlToValidate="tbUserName"
               ErrorMessage="The username must be 4 characters or longer"/>
       </td>
    </tr>
    <tr>
         <td valign="top">Password:</td>
       <td valign="top">
          <asp:Textbox id="tbPassword" runat="server" TextMode="password" />
       </td>
    </tr>
    <tr>
         <td align="right">
          <ASP:Button id="tbSubmit" runat="server" OnClick="Submit" text="Submit" />
       </td>
    </tr>
      </table>


CustomValidator for login page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>CustomValidator Control Sample</title>
    <script runat="server" language="C#">
      void CheckUniqueUserName(Object s, ServerValidateEventArgs e)
      {
        string username = e.Value.ToLower();
        if(username == "user" || username == "password")
        {
          e.IsValid = false;
        }
      }
      
      void submitButton_Click(Object s, EventArgs e)
      {
        if(Page.IsValid)
        {
          submitButton.Text = "Valid";
        }
        else
        {
          submitButton.Text = "Invalid!";
        }
      }
    </script>
  </head>
  <body>
    <form runat="server">
      
        New Username:<br />
        <asp:TextBox ID="usernameTextBox" runat="server" />
        <asp:CustomValidator ID="usernameUnique" runat="server"
            ControlToValidate="usernameTextBox"
            OnServerValidate="CheckUniqueUserName"
            ErrorMessage="This username already taken!" />
      
      
        <asp:Button ID="submitButton" runat="server"
            OnClick="submitButton_Click" Text="Submit" />
      
    </form>
</body>
</html>


CustomValidator for login page (VB)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>CustomValidator Control Sample</title>
    <script runat="server" language="VB">
      Sub CheckUniqueUserName(s As Object, _
            e As ServerValidateEventArgs)
        Dim username As String = e.Value.ToLower
        If (username = "user" Or username = "password") Then
          e.IsValid = False
        End If
      End Sub
      
      Sub submitButton_Click(s As Object, e As EventArgs)
        If Page.IsValid Then
          submitButton.Text = "Valid"
        Else
          submitButton.Text = "Invalid!"
        End If
      End Sub
    </script>
  </head>
  <body>
    <form id="Form1" runat="server">
      
        New Username:<br />
        <asp:TextBox ID="usernameTextBox" runat="server" />
        <asp:CustomValidator ID="usernameUnique" runat="server"
            ControlToValidate="usernameTextBox"
            OnServerValidate="CheckUniqueUserName"
            ErrorMessage="This username already taken!" />
      
      
        <asp:Button ID="submitButton" runat="server"
            OnClick="submitButton_Click" Text="Submit" />
      
    </form>
  </body>
</html>


Custom validator with Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingCustomValidator" %>
<!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>Using a CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    
    Enter a date:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="custDate" runat="server" 
       ControlToValidate="txtDate" 
       ValidateEmptyText="false"  
       Text="Enter a valid future date" 
       OnServerValidate="custDate_ServerValidate" />   
    
   <script type="text/javascript">
     function validateOrFields(source, args){
       var sUser = document.form1.<%= txtUser.ClientID %>.value;
       var sEmail = document.form1.<%= txtEmail.ClientID %>.value;
       
       if (sUser == "" && sEmail == "")
       {
          args.IsValid = false;
       }
       else
       {
          args.IsValid = true;
       }  
       return;  
     }
   </script>
   
   Enter user name:<br />
   <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
   <br />
   Enter email:<br />
   <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
   <asp:CustomValidator ID="OrFieldValidator" 
                        runat="server" 
                        Text="Enter either a user name or a email" 
                        ClientValidationFunction="validateOrFields"
                        OnServerValidate="OrFieldValidator_ServerValidate" />   
   
   
   <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
   
   </form>
</body>
</html>
<script type="text/javascript">
  ValidatorHookupControlID("<%= txtUser.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
  ValidatorHookupControlID("<%= txtEmail.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
</script>
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 UsingCustomValidator : System.Web.UI.Page
{
   protected void custDate_ServerValidate(object source, ServerValidateEventArgs args)
   {
      string sEnteredDate = args.Value;
      DateTime dt;
      bool convertSuccessful = DateTime.TryParse(sEnteredDate, out dt);
      if (convertSuccessful && dt >= DateTime.Today)
         args.IsValid = true;
      else
         args.IsValid = false;
   }
   protected void OrFieldValidator_ServerValidate(object source, ServerValidateEventArgs args)
   {
      if (txtUser.Text.Length <= 0 && txtEmail.Text.Length <= 0)
         args.IsValid = false;
      else
         args.IsValid = true;
   }
}


Performing validation against no particular field.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        if (!Page.IsPostBack)
            ResetStartTime();
    }
    void btnAgain_Click(Object sender, EventArgs e)
    {
        ResetStartTime();
    }
    void ResetStartTime()
    {
        Session["StartTime"] = DateTime.Now;
    }

    void valAnswer_ServerValidate(Object source, ServerValidateEventArgs args)
    {
        DateTime startTime = (DateTime)Session["StartTime"];
        if (startTime.AddSeconds(5) > DateTime.Now)
            args.IsValid = true;
        else
            args.IsValid = false;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Timed Test</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblQuestion"
        Text="What was Aristotle"s first name?"
        AssociatedControlID="txtAnswer"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtAnswer"
        Runat="server" />
    <asp:CustomValidator
        id="valAnswer"
        Text="(You answered too slowly!)"
        OnServerValidate="valAnswer_ServerValidate"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    <asp:Button
        id="btnAgain"
        Text="Try Again!"
        CausesValidation="false"
        OnClick="btnAgain_Click"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Use both client side and server side script to validate (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
   sub Submit(Sender as Object, e as EventArgs)
      if Page.IsValid then
         lblMessage.Text = "It"s all good!"
      end if
   end sub
   
   sub ValidateThis(Sender as Object, args as _
   ServerValidateEventArgs) 
   if len(args.Value) < 8 then
      args.IsValid = false
   else
      args.IsValid = true
   end if
end sub
</script>
<script language="JavaScript">
   function validateLength( oSrc, txtValue ){
      var retValue = true;
      if(txtValue.length < 8){
         retValue = false;
      }
      return retValue
   }
</script>
<html><body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server" />
      <table>
      <tr>
         <td valign="top">Username:</td>
       <td valign="top">
            <asp:Textbox id="tbUserName" runat="server" 
               /><br>
            <asp:CustomValidator runat="server"
               OnServerValidate="ValidateThis" 
               OnClientValiate="validateLength" 
               Display="Dynamic"
               ControlToValidate="tbUserName"
               ErrorMessage="The username must be 8 characters or longer"/>
       </td>
    </tr>
    <tr>
         <td align="right" colspan="2">
          <ASP:Button id="tbSubmit" runat="server" 
             OnClick="Submit" 
             text="Submit" />
       </td>
    </tr>
      </table>   
   </form>
</body></html>


Using the CustomValidator control to perform client-side validations

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(Object sender, EventArgs e) {
       Label1.Text = "VALID NUMBER!";
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>CustomValidator</title>
    <script language="JavaScript">
        function validateNumber(oSrc, args) {
           args.IsValid = (args.Value % 5 == 0);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
            Number: 
            <asp:TextBox ID="TextBox1" 
             Runat="server"></asp:TextBox>
             &nbsp;
            <asp:CustomValidator ID="CustomValidator1" 
             Runat="server" ControlToValidate="TextBox1" 
             ErrorMessage="Number must be divisible by 5" 
             ClientValidationFunction="validateNumber">
            </asp:CustomValidator>
        
        
            <asp:Button ID="Button1" OnClick="Button1_Click" 
             Runat="server" Text="Button"></asp:Button>
        
        
            <asp:Label ID="Label1" Runat="server"></asp:Label>
        
    </div>
    </form>
</body>
</html>


Using the CustomValidator control to perform server-side validations (C#)

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(Object sender, EventArgs e) {
         if (Page.IsValid) {
            Label1.Text = "VALID ENTRY!";
         }
    }
    void ValidateNumber(object source, ServerValidateEventArgs args)
    {
       try 
       {
          int num = int.Parse(args.Value);
          args.IsValid = ((num%5) == 0);
       }
       catch(Exception ex)
       {
          args.IsValid = false;
       }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
            Number: 
            <asp:TextBox ID="TextBox1" 
             Runat="server"></asp:TextBox>
             &nbsp;
            <asp:CustomValidator ID="CustomValidator1" 
             Runat="server" ControlToValidate="TextBox1" 
             ErrorMessage="Number must be divisible by 5" 
             OnServerValidate="ValidateNumber"></asp:CustomValidator>
        
        
            <asp:Button ID="Button1" OnClick="Button1_Click" 
             Runat="server" Text="Button"></asp:Button>
        
        
            <asp:Label ID="Label1" Runat="server"></asp:Label>
        
    </div>
    </form>
</body>
</html>


Using the CustomValidator control to perform server-side validations (VB)

<%@ Page Language="VB" %>
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
       If Page.IsValid Then
          Label1.Text = "VALID ENTRY!"
       End If
   End Sub
   Sub ValidateNumber(sender As Object, args As ServerValidateEventArgs)
       Try
          Dim num As Integer = Integer.Parse(args.Value)
          args.IsValid = ((num mod 5) = 0)
       Catch ex As Exception
          args.IsValid = False
       End Try
   End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
            Number: 
            <asp:TextBox ID="TextBox1" 
             Runat="server"></asp:TextBox>
            <asp:CustomValidator ID="CustomValidator1" 
             Runat="server" ControlToValidate="TextBox1" 
             ErrorMessage="Number must be divisible by 5" 
             OnServerValidate="ValidateNumber"></asp:CustomValidator>
        
        
            <asp:Button ID="Button1" OnClick="Button1_Click" 
             Runat="server" Text="Button"></asp:Button>
        
        
            <asp:Label ID="Label1" Runat="server"></asp:Label>
        
    </div>
    </form>
</body>
</html>


Validate a blank field

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void valProductCode_ServerValidate(Object source, ServerValidateEventArgs args)
    {
        if (args.Value.Length == 4)
            args.IsValid = true;
        else
            args.IsValid = false;
    }
</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" />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>


You can associate a custom validation function with the CustomValidator control.

ControlToValidate:        The ID of the form field being validated.
Text:                     The error message.

ClientValidationFunction: The name of a client-side function.
ServerValidate:           This event raised when the CustomValidator performs validation.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void valComments_ServerValidate(Object source, ServerValidateEventArgs args)
    {
        if (args.Value.Length > 10)
            args.IsValid = false;
        else
            args.IsValid = true;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblComments"
        Text="Comments:"
        AssociatedControlID="txtComments"
        Runat="server" />
    <asp:TextBox
        id="txtComments"
        TextMode="MultiLine"
        Columns="30"
        Rows="5"
        Runat="server" />
    <asp:CustomValidator
        id="valComments"
        ControlToValidate="txtComments"
        Text="(Comments must be less than 10 characters)"
        OnServerValidate="valComments_ServerValidate"
        Runat="server" />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>