Another in the 'things I didn't know but really should've done" - you can disable Client Side validation with client-side script... (English)

Another in the 'things I didn't know but really should've done" - you can disable Client Side validation with client-side script...

Tuesday, 16 March 2004

//

1 minute read

OK umm, actually quite embarassed about this one...I just discovered this was possible...so I can emit a bit of Javascript which lets me disable validation on a control when some condition is met here's this bit from MSDN:

Client-Side APIs

Some additional scenarios are enabled by functions that can be called from your client-side script.

Table 4. Functions called from client-side script

Name Description
ValidatorValidate(val) Takes a client-validator as input. Makes the validator check its input and update its display.
ValidatorEnable(val, enable) Takes a client-validator and a Boolean value. Enables or disables a client validator. Being disabled will stop it from evaluating and it will always appear valid.
ValidatorHookupControl(control, val) Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values.

Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.

Here is the previous example with a field that should only be validated when a check box is unchecked:

    public class Conditional : Page {
        public HtmlInputCheckBox chkSameAs;
        public RequiredFieldValidator rfvalShipAddress;
        public override void Validate() {
            bool enableShip = !chkSameAs.Checked;
            rfvalShipAddress.Enabled = enableShip;
            base.Validate();
        }
    }

Here is the client-side equivalent:

<input type=checkbox runat=server id=chkSameAs 
   onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
    var enableShip = !event.srcElement.status;
    ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
logo

© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.