Thursday, December 10, 2009

ASP.Net - Custom Validator – Multiple Controls

In ASP.Net, when you use a CustomValidator, it is easy to make it validate one control. But how do you use it to validate multiple controls (for eg: you want to make sure that if the City field has been filled out then you want the State field to also be filled out).

You first create your custom validator. But you do not assign it a ControlToValidate. Instead you add the following code to your aspx/ascx file:

<script type="text/javascript">
<!--
    ValidatorHookupControlID("<%= ctrlToValidate1.ClientID %>",
     document.getElementById("<%= customValidationCtrl.ClientID %>"));
    ValidatorHookupControlID("<%= ctrlToValidate1.ClientID %>",
     document.getElementById("<%= customValidationCtrl.ClientID %>"));
    ValidatorHookupControlID("<%= ctrlToValidate1.ClientID %>",
     document.getElementById("<%= customValidationCtrl.ClientID %>"));
//-->
</script>

The “ValidatorHookupControlID” method used above, is automatically injected into the page for you by ASP.Net whenever you use a validation control in your page.

One thing that I found is that I needed to add the code to the end of an ascx control, or next to the end of the form tag in an aspx page. Otherwise it throws an annoying JavaScript error.

1 comment:

Unknown said...

a bit more detail would have been appreciated. I don't have enough information to implement it at the moment.