Поделиться через


CustomValidator Control (General Reference)

Evaluates the value of an input control to determine whether it passes customized validation logic.

<asp:CustomValidator
    AccessKey="string"
    AssociatedControlID="string"
    BackColor="color name|#dddddd"
    BorderColor="color name|#dddddd"
    BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
        Inset|Outset"
    BorderWidth="size"
    ClientValidationFunction="string"
    ControlToValidate="string"
    CssClass="string"
    Display="None|Static|Dynamic"
    EnableClientScript="True|False"
    Enabled="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    ErrorMessage="string"
    Font-Bold="True|False"
    Font-Italic="True|False"
    Font-Names="string"
    Font-Overline="True|False"
    Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
        Large|X-Large|XX-Large"
    Font-Strikeout="True|False"
    Font-Underline="True|False"
    ForeColor="color name|#dddddd"
    Height="size"
    ID="string"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnServerValidate="ServerValidate event handler"
    OnUnload="Unload event handler"
    runat="server"
    SetFocusOnError="True|False"
    SkinID="string"
    Style="string"
    TabIndex="integer"
    Text="string"
    ToolTip="string"
    ValidateEmptyText="True|False"
    ValidationGroup="string"
    Visible="True|False"
    Width="size"
/>

Remarks

The CustomValidator control allows you to create a validation control with customized validation logic. For example, you can create a validation control that checks whether the value entered into a text box is an even number.

Validation controls always perform validation checking on the server. They also have complete client-side implementation that allows DHTML-supported browsers (such as Microsoft Internet Explorer 4.0 or later) to perform validation on the client. Client-side validation enhances the validation process by checking user input before it is sent to the server. This allows errors to be detected on the client before the form is submitted, avoiding the round-trip of information necessary for server-side validation.

To create a server-side validation function, provide a handler for the ServerValidate event that performs the validation. The string from the input control to validate can be accessed by using the Value property of the ServerValidateEventArgs object passed into the event handler as a parameter. The result of the validation is then stored in the IsValid property of the ServerValidateEventArgs object.

To create a client-side validation function, first add the server-side validation function described earlier. Next, add the client-side validation script function to the .aspx page.

If you are using Visual Basic, the function must be in the form:

Sub ValidationFunctionName (source, arguments)

If you are using JScript, the function must be in the form:

Function ValidationFunctionName (source, arguments)

Use the ClientValidationFunction property to specify the name of the client-side validation script function associated with the CustomValidator control. Because the script function is executed on the client, the function must be in a language that the target browser supports, such as Visual Basic or JScript.

Like server-side validation, using the Value property of the arguments parameter accesses the value to validate. Return the result of the validation by setting the IsValid property of the arguments parameter.

Security noteSecurity Note

When creating a client-side validation function, make sure you include the functionality of the server-side validation function. If you create a client-side validation function without a corresponding server-side function, it is possible for malicious code to bypass validation.

Multiple validation controls can be associated with an individual input control to validate different criteria. For example, you can apply multiple validation controls on a TextBox control that allows the user to enter the quantity of items to add to a shopping cart. You can use a CustomValidator control to ensure that the value specified is less than the amount in inventory and a RequiredFieldValidator control to ensure that the user enters a value into the TextBox control.

Note

If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.

It is possible to use a CustomValidator control without setting the ControlToValidate property. This is commonly done when you are validating multiple input controls or validating input controls that cannot be used with validation controls, such as the CheckBox control. In this case, the Value property of the arguments parameter passed to the event handler for the ServerValidate event and to the client-side validation function always contains an empty string (""). However, these validation functions are still called, where appropriate, to determine validity on both the server and the client. To access the value to validate, you must programmatically reference the input control you want to validate and then retrieve the value from the appropriate property. For example, to validate a CheckBox control on the server, do not set the ControlToValidate property of the validation control and use the following code for the handler for the ServerValidate event.

Sub ServerValidation (source As object, args As ServerValidateEventArgs)
 
   args.IsValid = (CheckBox1.Checked = True)

End Sub
void ServerValidation (object source, ServerValidateEventArgs args)
{
      
   args.IsValid = (CheckBox1.Checked == true);
   
}

For more information about the CustomValidator control, see the System.Web.UI.WebControls.CustomValidator class.

Examples

The following code example demonstrates how to create a CustomValidator control that validates whether the value entered in a text box is an even number on the server. The validation result is then displayed on the page.

Security noteSecurity Note

These code examples contain text boxes that accept user input, which poses a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
   <script runat="server">
      Sub ValidateBtn_OnClick(sender As object, e As EventArgs) 
         If Page.IsValid Then 
            lblOutput.Text = "Page is valid."
         Else 
            lblOutput.Text = "Page is not valid!"
         End If
      End Sub
      Sub ServerValidation (source As object, arguments As ServerValidateEventArgs)

         Dim num As Integer = Integer.Parse(arguments.Value)
         arguments.IsValid = ((num mod 2) = 0)
         
      End Sub
   </script>    
</head>
<body>
   <form runat="server">
      <h3>CustomValidator Example</h3>
      <asp:Label id=lblOutput runat="server" 
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" /><br>
      <p />
      <asp:TextBox id="Text1" 
           runat="server" />
      &nbsp;&nbsp;
      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           OnServerValidate="ServerValidation"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           runat="server"/>
      <p />
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>
   </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
   <script runat="server">
      void ValidateBtn_OnClick(object sender, EventArgs e) 
      { 
         if (Page.IsValid) 
         {
            lblOutput.Text = "Page is valid.";
         }
         else 
         {
            lblOutput.Text = "Page is not valid!";
         }
      }
      void ServerValidation (object source, ServerValidateEventArgs arguments)
      {

         int i = int.Parse(arguments.Value);
         arguments.IsValid = ((i%2) == 0);

      }
   </script>    
</head>
<body>
   <form runat="server">
      <h3>CustomValidator Example</h3>
      <asp:Label id=lblOutput runat="server" 
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" /><br>
      <p />
      <asp:TextBox id="Text1" 
           runat="server" />
      &nbsp;&nbsp;
      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           OnServerValidate="ServerValidation"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           runat="server"/>
      <p />
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>
   </form>
</body>
</html>

The following code example demonstrates how to create a CustomValidator control that performs the same validation routine as the previous example, but on the client.

<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
   <script runat="server">
      Sub ValidateBtn_OnClick(sender As object, e As EventArgs) 
         If Page.IsValid Then 
            lblOutput.Text = "Page is valid."
         Else 
            lblOutput.Text = "Page is not valid!"
         End If
      End Sub
      Sub ServerValidation (source As object, arguments As ServerValidateEventArgs)

         Dim num As Integer = Integer.Parse(arguments.Value)
         arguments.IsValid = ((num mod 2) = 0)
 
      End Sub
   </script>    
</head>
<body>
   <form runat="server">
      <h3>CustomValidator Example</h3>
      <asp:Label id=lblOutput runat="server" 
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" /><br>
      <p />
      <asp:TextBox id="Text1" 
           runat="server" />
      &nbsp;&nbsp;
      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           ClientValidationFunction="ClientValidate"
           OnServerValidate="ServerValidation"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           runat="server"/>
      <p />
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>
   </form>
</body>
</html>
<script language="javascript">
   <!--
   function ClientValidate(source, arguments)
   {
      if ((arguments.Value % 2) == 0)
         arguments.IsValid=true;
      else
         arguments.IsValid=false;
   }
   // -->
</script>
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
   <script runat="server">
      void ValidateBtn_OnClick(object sender, EventArgs e) 
      { 
         if (Page.IsValid) 
         {
            lblOutput.Text = "Page is valid.";
         }
         else 
         {
            lblOutput.Text = "Page is not valid!";
         }
      }
      void ServerValidation (object source, ServerValidateEventArgs arguments)
      {
         
            int i = int.Parse(arguments.Value);
            arguments.IsValid = ((i%2) == 0);

      }
   </script>    
</head>
<body>
   <form runat="server">
      <h3>CustomValidator Example</h3>
      <asp:Label id=lblOutput runat="server" 
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" /><br>
      <p />
      <asp:TextBox id="Text1" 
           runat="server" />
      &nbsp;&nbsp;
      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           ClientValidationFunction="ClientValidate"
           OnServerValidate="ServerValidation"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           runat="server"/>
      <p />
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>
   </form>
</body>
</html>
<script language="javascript">
   <!--
   function ClientValidate(source, arguments)
   {
      if ((arguments.Value % 2) == 0)
         arguments.IsValid=true;
      else
         arguments.IsValid=false;
   }
   // -->
</script>

See Also

Reference

CustomValidator

Other Resources

Validation Server Control Syntax