Hide asp.net panel with validation using Javascript
I need a way to hide/show an asp.开发者_开发问答net Panel with Validators inside using Javascript.
I have successfully hide a panel using this code below:
function ShowHidePanel(panelId, isShown) {
var pnl = document.getElementById(panelId);
if (pnl != null) {
if (isShown) {
pnl.style.display = 'block';
}
else {
pnl.style.display = 'none';
}
}
}
I am trying to disable all the validators inside using this code below:
function ToggleValidator(validatorId, enabled) {
var validator = document.getElementById(validatorId);
if (validator != null) {
ValidatorEnable(validator, enabled);
}
}
However, even though my panel is hidden, the validation on those validators inside is still firing.
Any thought will be appreciated.
You'll need jQuery and have to set the ValidationGroup property on your validators, but this should work.
$("#<%= pnlContainer.ClientID %>")
.find("span[validationGroup='MyValidationGroup']")
.each(function () { ValidatorEnable(this, false); });
You are hiding the panel on client side, so it will not have any effect on validators. They can access the control and hence fire the validations.
Disabling validator should work - only issue could be you are passing wrong id. You should use ClientID
property of server side validator control to refer to validator on client side.
Regardless, another work-around for your issue can be to disable associated controls in the panel when it's hidden. If the control is disabled then validator won't be fired.
I've run into the same problem and perhaps there's an more elegant fix but I've resorted to using custom validators for 'conditional' validation when needed.
For example, I only require SSN if the user selects a SSN radio button.
<asp:CustomValidator ID="cvSsn" runat="server" ControlToValidate="tbSsn"
EnableClientScript="true" Display="Dynamic" ValidateEmptyText="true"
ClientValidationFunction="onValidateSsn" OnServerValidate="OnValidateSSN"
Text="SSN required" ErrorMessage="SSN required" CssClass="validation-error"
ValidationGroup='Company' />
Javascript Client Side Validation:
function onValidateSsn(sender, args) {
var rbSsn = $('#<%= rbSsn.ClientID %>');
args.IsValid = !rbSsn.is(":checked") || isValidSSN(tbSsn.val());
}
In your case it may look something like the following
function onValidateField(sender, args)
{
if (!isShown)
{
args.IsValid = true;
return;
}
// preform validation
精彩评论