dotnet web sql business etc

22 квітня, 2011

Validating several controls with one customvalidator: using ValidatorHookupControl javascript function

Recently I have run into a seemingly simple problem: I had to make a control for picking a birth date.

First, I thought that using a MaskEdit control from AjaxControls toolkit would be the best fast and simple solution. However, then it turned out that MaskEdit is quite limited, in terms of validating date type input.

Afterwards, my colleagues recommended using dropdowns for days, months and years. That is easy, first we populate the dropdowns with the needed options (days 1-31, months Jan - Dec, years 1900-2011). Yet, there are some invalid combinations of values that can be entered by the user. Thus, input has to be validated, when either day, month, or year value changes, all three dropdowns have to be validated as a whole. This problem lead me to find out a solution on how to link several input controls to one custom validator by using ValidatorHookupControl.

First, we should define the following javascript function for our file:

function HookupControl(curObj, customValidatorClientID) {
         var customValidator = document.getElementById(customValidatorClientID);
         customValidator.controltovalidate =;
         customValidator.clientvalidationfunction = 

         ValidatorHookupControl(curObj, customValidator); }

this function links the input control (curObj) to your custom validator control (customValidator) at runtime.

Afterward, we should have HookupControl function run everytime user changes the value of either field (day, month, year). To do that, we have the define the following code for each of the dropdowns in the Page_Load event of the control (in addition to populating control with possible values):

ddlDay.Attributes.Add("onfocus", "HookUpControl(this,'" + customValidator.ClientID + "')");

Nice solution. Works as a charm!

Мітки: , ,

0 коментарі(в):

Дописати коментар

Підписка на Дописати коментарі [Atom]

<< Головна сторінка