Export (0) Print
Expand All
4 out of 6 rated this helpful - Rate this topic

CustomValidator Class

Performs user-defined validation on an input control.

For a list of all members of this type, see CustomValidator Members.

System.Object
   System.Web.UI.Control
      System.Web.UI.WebControls.WebControl
         System.Web.UI.WebControls.Label
            System.Web.UI.WebControls.BaseValidator
               System.Web.UI.WebControls.CustomValidator

[Visual Basic]
Public Class CustomValidator
   Inherits BaseValidator
[C#]
public class CustomValidator : BaseValidator
[C++]
public __gc class CustomValidator : public BaseValidator
[JScript]
public class CustomValidator extends BaseValidator

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

Use the CustomValidator control to provide a user-defined validation function for an input control. The CustomValidator control is a separate control from the input control it validates, which allows you to control where the validation message is displayed.

Validation controls always perform validation on the server. They also have complete client-side implementation that allows DHTML-supported browsers (such as Internet Explorer 4.0 and 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, thus 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 passed into the event handler as a parameter. The result of the validation is then stored in the IsValid property of the ServerValidateEventArgs.

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 ASP.NET (.aspx) page.

If you are using VBScript, 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. Because the script function is executed on the client, the function must be in a language that the target browser supports, such as VBScript or JScript.

Like server-side validation, the string from the input control to validate is accessed by using the Value property of the arguments parameter. Return the result of the validation by setting the IsValid property of the arguments parameter.

CAUTION   When creating a client-side validation function, be sure to also 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 used 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 require the user to enter data in the 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 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.

[Visual Basic] 
Sub ServerValidation (source As object, args As ServerValidateEventArgs)
 
   args.IsValid = (CheckBox1.Checked = True)
End Sub
[C#] 
void ServerValidation (object source, ServerValidateEventArgs args)
{
      
   args.IsValid = (CheckBox1.Checked == true);
   
}

For additional information on validation controls, see BaseValidator.

Example

[Visual Basic, C#] The following example demonstrates how to create a server-side CustomValidator.

[Visual Basic] 

<%@ Page Language="VB" AutoEventWireup="True" %>

<html>
<head>

   <script runat="server">

      Sub ValidateBtn_OnClick(sender As Object, e As EventArgs) 

         ' Display whether the page passed validation.
         If Page.IsValid Then 

            Message.Text = "Page is valid."

         Else 

            Message.Text = "Page is not valid!"

         End If

      End Sub

      Sub ServerValidation(source As Object, args As ServerValidateEventArgs)

         Try 

            ' Test whether the value entered into the text box is even.
            Dim num As Integer = Integer.Parse(args.Value)
            args.IsValid = ((num mod 2) = 0)
 
         Catch ex As Exception
         
            args.IsValid = false

         End Try

      End Sub

   </script>    

</head>
<body>

   <form runat="server">
  
      <h3>CustomValidator ServerValidate Example</h3>

      <asp:Label id="Message"
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" 
           runat="server" />

      <p>

      <asp:TextBox id="Text1" 
           runat="server" />
    
      &nbsp;&nbsp;

      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           OnServerValidate="ServerValidation"
           runat="server"/>

      <p>
 
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>

   </form>
  
</body>
</html>


[C#] 

<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>

   <script runat="server">

      void ValidateBtn_OnClick(object sender, EventArgs e) 
      { 

         // Display whether the page passed validation.
         if (Page.IsValid) 
         {

            Message.Text = "Page is valid.";

         }

         else 
         {

            Message.Text = "Page is not valid!";

         }

      }

      void ServerValidation(object source, ServerValidateEventArgs args)
      {

         try 
         {

            // Test whether the value entered into the text box is even.
            int i = int.Parse(args.Value);
            args.IsValid = ((i%2) == 0);

         }

         catch(Exception ex)
         {

            args.IsValid = false;

         }

      }

   </script>    

</head>
<body>

   <form runat="server">
  
      <h3>CustomValidator ServerValidate Example</h3>

      <asp:Label id="Message"  
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" 
           runat="server"/>

      <p>

      <asp:TextBox id="Text1" 
           runat="server" />
    
      &nbsp;&nbsp;

      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Text1"
           Display="Static"
           ErrorMessage="Not an even number!"
           ForeColor="green"
           Font-Name="verdana" 
           Font-Size="10pt"
           OnServerValidate="ServerValidation"
           runat="server"/>

      <p>
 
      <asp:Button id="Button1"
           Text="Validate" 
           OnClick="ValidateBtn_OnClick" 
           runat="server"/>

   </form>
  
</body>
</html>

[Visual Basic, C#] The following example demonstrates how to create a client-side CustomValidator.

[Visual Basic] 

<%@ Page Language="VB" AutoEventWireup="True" %>

<html>
<head>

   <script runat="server">

      Sub ValidateBtn_OnClick(sender As Object, e As EventArgs) 

         ' Display whether the page passed validation.
         If Page.IsValid Then 

            Message.Text = "Page is valid."

         Else 

            Message.Text = "Page is not valid!"

         End If

      End Sub

      Sub ServerValidation(source As Object, args As ServerValidateEventArgs)

         Try 

            ' Test whether the value entered into the text box is even.
            Dim num As Integer = Integer.Parse(args.Value)
            args.IsValid = ((num mod 2) = 0)
 
         Catch ex As Exception
         
            args.IsValid = false

         End Try

      End Sub

   </script>      

</head>
<body>

   <form runat="server">
  
      <h3>CustomValidator ServerValidate Example</h3>

      <asp:Label id="Message"  
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" 
           runat="server"/>

      <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="vbscript">

   <!--

   Sub ClientValidate(source, arguments)
            
      If (arguments.Value mod 2) = 0 Then
         arguments.IsValid=true
      Else
         arguments.IsValid=false
      End If

   End Sub

   ' -->

</script>



[C#] 

<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>

   <script runat="server">

      void ValidateBtn_OnClick(object sender, EventArgs e) 
      { 

         // Display whether the page passed validation.
         if (Page.IsValid) 
         {

            Message.Text = "Page is valid.";

         }

         else 
         {

            Message.Text = "Page is not valid!";

         }

      }

      void ServerValidation(object source, ServerValidateEventArgs args)
      {

         try 
         {

            // Test whether the value entered into the text box is even.
            int i = int.Parse(args.Value);
            args.IsValid = ((i%2) == 0);

         }

         catch(Exception ex)
         {

            args.IsValid = false;

         }

      }

   </script>    

</head>
<body>

   <form runat="server">
  
      <h3>CustomValidator ServerValidate Example</h3>

      <asp:Label id="Message"  
           Text="Enter an even number:" 
           Font-Name="Verdana" 
           Font-Size="10pt" 
           runat="server"/>

      <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="vbscript">

   <!--

   Sub ClientValidate(source, arguments)
            
      If (arguments.Value mod 2) = 0 Then
         arguments.IsValid=true
      Else
         arguments.IsValid=false
      End If

   End Sub

   ' -->

</script>


[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Web.UI.WebControls

Platforms: Windows 2000, Windows XP Professional, Windows Server 2003 family

Assembly: System.Web (in System.Web.dll)

See Also

CustomValidator Members | System.Web.UI.WebControls Namespace | BaseValidator | RequiredFieldValidator | ClientValidationFunction | ServerValidate | OnServerValidate | ServerValidateEventArgs | Value | IsValid

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.