[This was originally posted at
http://timstall.dotnetdevelopersjournal.com/disable_validators_on_the_client.htm]
Sometimes you may want client-side activities to disable a validator. For example, suppose a TextBox is only required if a CheckBox is selected. The TextBox could have a RequiredValidator, but we'd like selecting the CheckBox to enable/disable that validator at the client.
One approach is to use JavaScript functions from the WebUIValidation.js file located at: aspnet_client\system_web\1_1_4322. This stores the script used by ASP.Net's validators and is available to all pages. It includes a script, ValidatorEnable, which takes a control and a boolean and sets the control's Enabled property to the boolean value.
For example, you could have the onclick of a checkbox (id=ChkEnable), call the custom javascript below.
function EnableValidator() { var blnEnabled = document.Form1.ChkEnable.checked; ValidatorEnable(document.getElementById("RequiredFieldValidator1"),blnEnabled); }
|
We still need to persist these changes to the server. We can simply enable/disable the validator in the page load:
this.RequiredFieldValidator1.Enabled = this.ChkEnable.Checked;
|
In summary, ASP.Net provides easy ways to disable a validator based on client activity. This lets us extend the default validator functionality.