Archive for June, 2011

How it works: ASP.NET Custom Validator

Thursday, June 23rd, 2011

This time I will highlight how ASP.NET validator works (in particular the Custom Validator). This control has almost the same attributes as the other validation controls, but with Custom Validator you can specify your own method (Server code and Client script) to validate.

When to use ASP.NET Custom Validator?

Custom Validator is a suitable for the following scenario:

  • Validating checkbox (Agreements, Terms and Conditions checkbox). Please note that you cannot use Required Field validator for check box control.
  • Validation that involves multiple controls. For example: provide at least one telephone number from three available inputs (mobile, work phone, and home phone text boxes).
  • Validation that involves certain calculation or custom logic

How to use ASP.NET Custom Validator

You can assign two validation functions into Custom Validator. They are Server side in code behind and client script (VB or JavaScript).

  1. Create the server side function in code behind to validate the values in server (mandatory). This is important because we do not have control over the client script and it can be easily bypassed.
    Public void ServerValidation (object source, ServerValidateEventArgs arguments)
    {
    int i = int.Parse(arguments.Value);
    arguments.IsValid = ((i%2) == 0);
    }
  2. Create the client side JavaScript function to create validation on client side.
    <script language="javascript">
    function ClientValidate(source, arguments)
    {
    if ((arguments.Value % 2) == 0)
    arguments.IsValid=true;
    else
    arguments.IsValid=false;
    }
    </script>

Your Control will look like

<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
runat="server" />

Why Custom Validator is not working

  • Do not set ControlToValidate, if you want to validate multiple fields. Since Custom Validator will not run if the ControlToValidate is empty value.
  • Call Page_ClientValidate(); in JavaScript and Page.IsValid in Page Behind to check if the validation is fulfilled.

Further Information

http://msdn.microsoft.com/en-us/library/9eee01cx%28VS.90%29.aspx