The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Mar 2010»»
SMTWTFS
  12
3
456
7
8
9
10
111213
14151617181920
21222324252627
28293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Validation Tips for Validators

posted Wednesday, 19 October 2005

ASP.Net provides a convenient, pre-built validation system. It consists of individual validation controls (like required fields), custom validators, potentially your own controls derived from BaseValidator, and a summary control to tie it all together

Sometimes we want to force, or bypass, validation on the client. We can do this by calling ASP.Net's own auto-generated functions. Drag a Required Validator onto a WebForm, run it, view the page source, and you'll see some javascript auto-generated by ASP.Net. This includes both a Page_ClientValidate and __doPostBack function.

GoalExplanationHow to do it
Force validation on the client Be able to check as much at the client before posting back. call Page_ClientValidate()
Bypass client validation checksBe able to have certain controls bypass validation checks. For example you may two unrelated sections on a page, and you'll want to click a "calculate" or "search" button on the first section without triggering the unrelated validators on the other section.call postBack: __doPostBack('','')

Also keep in mind as you develop your validation system:

  • Validators (including custom) don't fire if their ControlToValidate fields are empty (except for RequiredValidator itself).
  • Recall that disabled html fields do not persist their value to the server. This may throw off validators on fields that the user can disable at run time.
  • You can debug you client side validators, as they are just JavaScript.

ASP.Net provides custom validators. These are great for fine-tuning your validation. Some tips to keep in mind:

  • You can embed extra attributes in the validator's innerHtml, and then reference them in the client & server functions. This is useful to make validators reusable (control independent).
  • You can omit the controlToValidate property to ensure that validation only fires on postback as opposed to when focus leaves that individual control. This is very useful when validating groups of controls.
  • You can use the methods in WebUIValidation.js to access and compare values.
  • You need both client and server validation functions.

Here's a sample custom validator:

Client Code - Validator Html:

<asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="CustomValidator"
MaxLength="10"
ControlToValidate="File1"
ClientValidationFunction="ValidateMaxLength"
OnServerValidate="ValidateMaxLength">
</
asp:CustomValidator
>

Here we added the MaxLength attribute. We can reference it in both the client and server validation functions.

Client Code - JavaScript validation function:

    <script language="javascript">

       function ValidateMaxLength(source, arguments)
       {
              var intMaxLength = source.MaxLength;
              if (arguments.Value.length > intMaxLength)
                  arguments.IsValid = false;
              else
                  arguments.IsValid = true;
       }
    </script
>

Server Code - validation function:

    protected void ValidateMaxLength (object source,
    ServerValidateEventArgs value) 
    {
      try 
      {
        int intMaxLength = Convert.ToInt32(
        ((System.Web.UI.WebControls.CustomValidator)source
        ).Attributes["MaxLength"] );

        if (value.Value.Length > intMaxLength)
          value.IsValid = false;
        else
          value.IsValid = true;
      }
      catch 
      {
        value.IsValid = false;
      }
    }

links: digg this    technorati    




1. some_guy left...
Tuesday, 10 January 2006 3:58 pm

For some reason VS2003 yelled at me for embedding the extra attributes like MaxLength in the Custom Validator. In fact, it failed everytime. As such, I have a hardcoded (sadly) max length in the javascript... thanks for the tips


2. Tim Stall left...
Friday, 13 January 2006 9:36 am

That may be because "MaxLength" already exists as an attribute, and gets rendered in all -lowercase as "maxlength", and therefore there's a conflict in duplicate attributes. If you added an attribute like "maxlength_2", then would it work?