We often come into problems with .NET validators on elements that are hidden using javascript/css (ie. display:none)
For example (there may be syntax errors but don't worry about it)
<asp:CheckBox ID="chkNewsletter" runat="server" Checked="true" />
...
<div id='newsletterOnly'>
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="vldEmail" ControlToValidate="txtEmail" ErrorMessage="Required" runat="server" />
</div>
with JavaScript:
$('#chkNewsletter').changed(function() {
$(this).is(':checked') ? $('#newsletterOnly').show() : $('#newsletterOnly').hide();
});
It should not validate txtEmail if it is hidden.
You can't submit the form if newsletterOnly is hidden, because the RequiredFieldValidator is still effective eventhough it is hidden :(
And you can't even see the validator error message because it is hidden
Is there any way around this?
I am trying to avoid PostBacks to improve user experience.
I wish I could modify .NET javascript to validate controls only when they are visible.
I wrote this as a general solution (can be used on all .NET websites).
You only need to add an OnClientClick to the submit button.
//===================================================================
// Disable .NET validators for hidden elements. Returns whether Page is now valid.
// Usage:
// <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="DisableHiddenValidators()" />
//===================================================================
function DisableHiddenValidators() {
for (var i = 0; i < Page_Validators.length; i++) {
var visible = $('#' + Page_Validators[i].controltovalidate).is(':visible');
ValidatorEnable(Page_Validators[i], visible)
}
return Page_ClientValidate();
}
To use it, simply include the above javascript and add the class OnClientClick="DisableHiddenValidators()"
to the submit button:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="DisableHiddenValidators()" />
EDIT:
jQuery $(submitButton).click
function didn't work on iPhone/Android. I have changed the sample code above slightly.
If anyone see anything wrong or possible improvements please comment :)
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