ASP.Net/Validation by Control/CustomValidator

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

asp CustomValidator: validate event function (C#)

   <source lang="csharp">

<%@ 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">
   <asp:Label  
       id="lblProductCode"
       Text="Product Code:"
       AssociatedControlID="txtProductCode"
       Runat="server" />
   
<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" />
   </form>

</body> </html>

      </source>
   
  


asp:CustomValidator validation (VB.net)

   <source lang="csharp">

<%@ 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">

<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">
   
You must enter a number that is divisible by 9!

</asp:CustomValidator>

<asp:button

   id="butOK"
   text="OK"
   Type="Submit"
   runat="server"

/> </Form> </BODY> </HTML>

      </source>
   
  


Client side and server side validation

   <source lang="csharp">

<%@ 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">
       <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" />  
       <asp:CustomValidator 
            ControlToValidate="txtValue" 
            ValidateEmptyText=false
            ID="CustomValidator1" runat="server" 
            ClientValidationFunction="ClientValidator" 
            OnServerValidate="ServerValidator">
               Please enter an even number
       </asp:CustomValidator>
   
   </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
   }
 }

}

</source>
   
  


Customvalidator Demo (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html> <head>

  <title>Validation Control Example</title>
   <script language="javascript">
   
  </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>

Validation Control Example

  <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:
              

Enter a 4-digit year </asp:tablecell> <asp:tablecell runat="server"> <asp:textbox id="year" runat="server"/>
<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:

Enter an integer between 0 and 100 </asp:tablecell> <asp:tablecell runat="server"> <asp:textbox id="value" runat="server"/>
<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>

      </source>
   
  


CustomValidator: value length less than 100 (C#)

   <source lang="csharp">

<%@ 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">
   <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" />
   </form>

</body> </html>

      </source>
   
  


Define your own logic with CustomValidator

   <source lang="csharp">

<%@ 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"/>

<asp:label runat="server" id="theFeedback"/>
<asp:button type="submit" runat="server" Text="Submit" /> </form> </body> </html>

</source>