Sunday, June 12, 2005

Using WebUIValidation.js in your own controls

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

ASP.Net includes several validator controls. These controls first validate data on the client using JavaScript. Much of the scripting for this is contained in the WebUIValidation.js file, which is in an IIS directory like \aspnet_client\system_web\1_1_4322. Each page containing any validator already includes this script, therefore you can reuse any of its functions in your own controls. For example, view the source of an aspx.page that has a validator on it, and you'll see a reference to the WebUIValidation.js file. Because it's a bunch of free methods, lets look at this file to see how we can benefit from it.

The file has many functions. I've included descriptions for some of the more relevant ones:

  • ValidatorUpdateDisplay(val)
  • ValidatorUpdateIsValid()
  • ValidatorHookupControlID(controlID, val)
  • ValidatorHookupControl(control, val)
  • ValidatorGetValue(id) - gets the value of a control given its Id
  • ValidatorGetValueRecursive(control)
  • Page_ClientValidate()
  • ValidatorCommonOnSubmit()
  • ValidatorEnable(val, enable) - can enable/disable a specific validator
  • ValidatorOnChange()
  • ValidatorValidate(val)
  • ValidatorOnLoad()
  • ValidatorConvert(op, dataType, val)
  • ValidatorCompare(operand1, operand2, operator, val)
  • CompareValidatorEvaluateIsValid(val) - used by Compare Validator
  • CustomValidatorEvaluateIsValid(val)  - used by Custom Validator
  • RegularExpressionValidatorEvaluateIsValid(val) - used by Regular Expression Validator
  • ValidatorTrim(s) - trims excess white space from input
  • RequiredFieldValidatorEvaluateIsValid(val) - used by Required Field Validator
  • RangeValidatorEvaluateIsValid(val) - used by Range Validator
  • ValidationSummaryOnSubmit()

The ID (such as in the ValidatorGetValue) indicates a string. The 'val' parameter indicates the Validator control itself, not just the ID. I previously wrote about how to use the ValidatorEnable to Disable Validators on the Client. However you can use other methods to get the value of a control or extend existing validator functionality. This is almost essential if you're going to build your own validators by deriving from BaseValidator.

JavaScript can be messy to many developers, and it's helpful to know that such a toolbox of production-ready scripts is already available to your pages.

No comments:

Post a Comment