Tuesday, October 18, 2005

Validation Tips for Validators

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/validation_tips_for_validators.htm]

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"

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;
                  arguments.IsValid = true;

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;      }    }

No comments:

Post a Comment