ASP.Net/Validation by Control/CustomValidator

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

asp CustomValidator: validate event function (C#)

<%@ Page Language="C#" %>
<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" />
    
    <br /><br />
    
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />    
    
    </div>
    </form>
</body>
</html>



asp:CustomValidator validation (VB.net)

<%@ Page Language=VB Debug=true %>
<%@ Import Namespace="System.Data" %>
<script runat=server>
Sub ServerValidation9 (source As object, E As ServerValidateEventArgs)
    If E.Value mod 9 = 0 Then
        E.IsValid = True
    Else
        E.IsValid = False
    End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>CustomValidator Control Sample Page</TITLE>
</HEAD>
<BODY >
<form runat="server">
<Font Face="Tahoma">
<BR><BR>
<asp:Label
    id="lblMessage"
    runat="server"
    Font-Bold="True"
    Text="Enter a multiple of 9"
/>
<asp:TextBox 
    id="txt9" 
    Columns="25"
    MaxLength="30"
    runat=server 
/>
<asp:CustomValidator 
    id="custom9"
    ControlToValidate="txt9"
    OnServerValidate="ServerValidation9"
    Display="Dynamic"
    Font-Name="Verdana"
    Font-Bold="True"
    Font-Size="10pt"
    runat="server">
    <BR>You must enter a number that is divisible by 9!
</asp:CustomValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    Type="Submit"
    runat="server"
/>
</Font>
</Form>
</BODY>
</HTML>



Client side and server side validation

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="Default_aspx" %>
<!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">
<script language="javascript">
   function ClientValidator(source, args)
   {
      if (args.Value % 2 == 0)
         args.IsValid=true;
      else
         args.IsValid=false;
      return;
   }
</script>
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Submit" />&nbsp;&nbsp;
        <asp:CustomValidator 
             ControlToValidate="txtValue" 
             ValidateEmptyText=false
             ID="CustomValidator1" runat="server" 
             ClientValidationFunction="ClientValidator" 
             OnServerValidate="ServerValidator">
                Please enter an even number
        </asp:CustomValidator>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
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 Default_aspx : System.Web.UI.Page 
{
  protected void ServerValidator(object source, ServerValidateEventArgs e)
  {
    try
    {
      int evenNumber = Int32.Parse(e.Value);
      if (evenNumber % 2 == 0)
        e.IsValid = true;
    }
    catch (Exception)
    {
      // error handler here
    }
  }
}



Customvalidator Demo (VB.net)

<%@ Page Language="vb" %>
<html>
<head>
   <title>Validation Control Example</title>
    <script language="javascript">
    <!--
      function ClientValidate(source, arguments)
      {
         //alert(arguments.Value);
         var r, re;      //Declare variables.
         re = new RegExp(/^[1-9][0-9][0-9][0-9]$/);  //Create regular expression object.
         r = re.test(arguments.Value);  //Test for match.
         arguments.IsValid = r;    //Return results.
      }
   -->
   </script>
   <script runat="server">
      Sub Page_Load()
         vsSummary.DisplayMode = ValidationSummaryDisplayMode.List
      End Sub
      Sub ServerValidation (source As object, args As ServerValidateEventArgs)
         Dim RegExVal As New System.Text.RegularExpressions.Regex("^\d{4}$")
         If RegExVal.IsMatch(args.Value) Then
            args.IsValid = True
         Else
            args.IsValid = False
         End If
      End Sub
   </script>
</head>
<body>
   <h1>Validation Control Example</h1>
   <form runat="server">
      <asp:table id="MyTable" border="1" cellpadding="5" cellspacing="0" runat="server">
         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               CustomValidator Control:
               <br><br>
               Enter a 4-digit year
            </asp:tablecell>
            <asp:tablecell runat="server">
               <asp:textbox id="year" runat="server"/><br>
               <asp:customvalidator id="cvDate" 
                  controltovalidate="year"
                  errormessage="Not a valid year!"
                  onservervalidate="servervalidation"
                  clientvalidationfunction="ClientValidate"
                  display="dynamic"
                  runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               RangeValidator Control:
               <br><br>
               Enter an integer between 0 and 100
            </asp:tablecell>
            <asp:tablecell runat="server">
               <asp:textbox id="value" runat="server"/><br>
               <asp:rangevalidator id="rvCompare"
                  controltovalidate="value" 
                  minimumvalue="0"
                  maximumvalue="100" 
                  type="integer" 
                  errormessage="Value not in valid range!" 
                  runat="server"/>
            </asp:tablecell>
         </asp:tablerow>

         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               ValidationSummary Control:
            </asp:tablecell>
            <asp:tablecell runat="server">
               <asp:validationsummary id="vsSummary"
                  displaymode="bulletlist" 
                  headertext="Page has the following errors: "
                  showsummary="true" 
                  showmessagebox="false"
                  runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
         <asp:tablerow runat="server">
            <asp:tablecell colspan="2" runat="server">
               <asp:button text="submit" runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
      </asp:table>
      <asp:label id="MyLabel" runat="server"/>
   </form>
</body>
</html>



CustomValidator: value length less than 100 (C#)

<%@ Page Language="C#" %>
<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" />
    <br />    
    <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" />
        
    <br /><br />
    
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>



Define your own logic with CustomValidator

<%@ Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server" language="C#">
protected void ServerAddMoreValidation(object o, ServerValidateEventArgs e) {
    try {
        int theInput = Int32.Parse(e.Value);
        if (theInput < 0) {
            theValidator.ErrorMessage = "please enter a positive value";
        }
        else {
            theValidator.ErrorMessage = "please enter at least " + (theInput + 1).ToString();
        }
    }
    catch {
    }
    e.IsValid = false;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Target Page</title>
</head>
<body>
<form runat="server">
Enter the quantity:
<asp:textbox runat="server" id="quantity" />
<asp:CustomValidator 
    runat="server"
    id="theValidator" 
    ControlToValidate="quantity"
    OnServerValidate="ServerAddMoreValidation" 
    ErrorMessage="Try Again"/><br />
<asp:label runat="server" id="theFeedback"/><br />
<asp:button type="submit" runat="server" Text="Submit" />
</form>
</body>
</html>