Warning: Please consider that this post is over 9 years old and the content may no longer be relevant.
This function takes the validator control (val) and a boolean to determine whether it should be enabled or disabled. The problem with this function is that it triggers the validator to validate itself immediately, showing any validation error messages before the user has submitted the form, which may not always be want you want. The alternative is to set the validator’s enabled property to trigger this validator to validate itself when the user submits the form, and by using the Page_IsValid variable you can test whether the user has triggered a validation or not, then use ValidatorEnable function only after the validation has occurred when the user expects to see validation messages.
Consider a scenario where you want the user to enter their address only if they select Australia as the country, you also need to validate the address fields. Two ways to approach this are:
- For each address field you need to validate use a CustomValidator control, and in the ClientValidationFunction first check to see if the country is set to Australia and if it’s not then consider any response for this control as valid. The problem with this is you will have to recrete all of the validator functionality in your client validation function, which means more work.
If Page_IsValid is false then assume the user has tried to submit but failed, in this case we expect validation messages to show / hide as the user changes data on the form - this is the normal ASP.Net behaviour.
Here’s an example:
Don’t forget to include server side code to mimic this enabling / disabling of validators. To do this override the Validate() function, enable or disable validators depending on the country selected and call the base.Validate() function.