Pakk Pakk - 11 months ago 45
ASP.NET (C#) Question

Enable/Disable aspx Validator via js not holding true in code behind?

I'd like to know what I'm missing regarding disabling these via js only, and not having to add repeat code in the code behind.

I'm using this code to disable / enable Validators:

validator: {
enable: function (id) {
var validator = document.getElementById(id);
ValidatorEnable(validator, true);
disable: function (id) {
var validator = document.getElementById(id);
ValidatorEnable(validator, false);

It works great, until i make a postback to save some data, ... where these disabled validators are not disabled.

So i have to run some repeated code within the OnLoad() if IsPostBack is true to disable the validators I've disabled via js already.

Edit: Removed any code as it wasn't required to achieve an answer. Answer: Server side must also disable the elements, can't be done explicitly for these reasons: found here, thanks to @ConnersFan:

  • Some validation controls may not support client scripting. A good example: if you are using a CustomValidator with a server validation function but no client validation function.

  • Security considerations. Someone can very easily take a page with script and disable or change it. You should not rely on script to stop bad data getting into to your system, only to provide more immediate feedback to your users. For this reason, if you are using a CustomValidator, you should not provide a client validation function without a corresponding server validation function.

Answer Source

As you can see in ASP.NET Validation in Depth, the prefered method to enable/disable a validator on the client side is to use ValidatorEnable:

var validator = document.getElementById(id);
ValidatorEnable(validator, false);

On the server side, you must also enable/disable the validator explicitely (I don't think you can avoid that):

validator.Enabled = false;

This change will be preserved in client code, unlike the change in Javascript code which is not preserved on the server side.