I have a drop down (dropdown2) that is required IF there is something in it but it's options data is driven by ajax from another dropdown (dropdown1) selection. Sometimes dropdown2 will be empty and in that case I can't require it. So I can disable the requiredFieldValidators
in javascript by calling this...
ValidatorEnable(document.getElementById(validatorId), false);
This works fine but the server still fires the requiredFieldValidator
logic. Is anyone aware of how I can force the server to not validate if the validator is set to false client side?
DISABLE
document.getElementById("<%=ReqVal.ClientID%>").style.visibility = "hidden";
document.getElementById("<%=ReqVal.ClientID%>").enabled = false;
ENABLE
document.getElementById("<%=ReqVal.ClientID%>").style.visibility = "visible";
document.getElementById("<%=ReqVal.ClientID%>").enabled = true;
Why don't you just use a client side validator? You are making your job much more difficult doing this. If you have access to it via the clientside, why are you bothering hitting it at the serverside?
The only other thing I can think of is to create a hidden field and set it via the client side, and then when you do a postback to check this value and disable / enable the validator.
For example after this:
JS:
ValidatorEnable(document.getElementById(validatorId), false);
var hidden = document.getElementById(hiddenID);
hidden = "1";
Then in your load event:
If (hidden = "1") then
validator.enabled=false
end if
Take a look at this post, very similiar to yours: ASP.NET - how to stop unrequired server validation
Require Validators are injected in the DOM as span elements.
If you are using JQUERY, get the element using a jQuery Selector, then get the DOM element from that selection an you are set.
Here is an example:
Lets say you have a require validator id="MyReqValidator".
In your javascript file you will do:
//The jQuery Element:
jqValidator = $("span[id$=MyReqValidator]");
//No the DOM element. This is what document.getElementById would return.
domValidator = jqValidator.get(0)
//Now enable your validator:
ValidatorEnable(validator, true);
All in one line of code
ValidatorEnable( $("span[id$=MyReqValidator]").get(0), true);
So I didn't get JonH answer to work, and the rest is only client side. So this is my solution:
To disable a RequiredFieldValidator on the client side:
ValidatorEnable(document.getElementById("rfv"), false);
To disable a RequiredFieldValidator on the server side you can override the Validate() method like this:
public override void Validate()
{
bool disableRfv = input_to_check <> 1;
rfv.Enabled = disableRfv;
base.Validate();
}
Or, in VBasic:
Public Overrides Sub Validate()
Dim disable_rfv As Boolean = input_to_check <> 1
rfv.Enabled = disable_rfv
MyBase.Validate()
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With