Topic: Validation - Customized
Share/Save/Bookmark
C# Validation - Customizing
 
To perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write
code to perform the validation on the server side and (optionally) on the client side
 
SERVER SIDE
On the server side, place your validation code in the "ServerValidate" event procedure. The arguments to this procedure provide
access to the control to validate. The following event procedure validates that an entered number is prime.
 
private void vldtxtPrime_ServerValidate(object sender, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
   try
   {
      // Get valie from ControlToValidate (passed as args)
      int iPrime = Int32.Parse(args.Value);
      for (int iCount = 2; iCount <= (iPrime / 2); iCount++)
      {
         // If number is evenly divisible, it's not prime, return false
         if((iPrime % iCount) == 0)
         {
            args.IsValid = false;
            return;
         }
         // Number is prime, return True
         agrs.IsValid = true;
         return;
      }
   }
   catch(Exception e)
   {
      // If there was an error parsing, return false
      args.IsValid = false;
      return;
   }
}
 
CLIENT SIDE
To privide client-side validation, specify a validation script in the CustomValidator control's "ClientValidationFunction" property.
Client-side validation is optional, and if you provide it, you should maintain similar validation code in both places. The following
script provides a client-side version of the prime number validation performed on the server:
 
1. Put the script in Web form's HTML section
2. Put the method name in the CustomValidator control's "ClientValidationFunction" property
 
VBScript
<script langueage="vbscript">
   Sub ClientValidate(source, arguments)
      For iCount = 2 To arguments.Value \ 2
         ' if number is evenly divisible, it's not prime return false
         If arguments.Value Mod iCount = 0 Then
            arguments.IsValid = False
            Exit Sub
         End if
      Next
      arguments.IsValid = True
   End Sub
</script>
 
JScript
<script language="jscript">
   function ClientValidate(source, arguments)
   {
      for (var iCount = 2; iCount <= arguments.Value / 2; iCount++)
      {
         // If number is evenly divisible, it's not prime Return false
         if ((arguments.Value % iCount) == 0)
         {
            arguments.IsValud = false;
            return false;
         }
      }
      // Number is prime, return True
      arguments.IsValid = true;
      return true;
   }
</script>