|
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.
| Goal | Explanation | How 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 checks | Be 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:
ASP.Net provides custom validators. These are great for fine-tuning your validation. Some tips to keep in mind:
Here's a sample custom validator:
Client Code - Validator Html:
|
Here we added the MaxLength attribute. We can reference it in both the client and server validation functions.
Client Code - JavaScript validation function:
|
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; } } |
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