Ignore .NET validators if element is hidden (display: none)

We often run into problems with .NET checks on elements that are hidden using javascript / css (i.e. 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(); }); 

Do not check txtEmail if it is hidden.
You cannot submit the form if newsletterOnly is hidden, because RequiredFieldValidator is still effective, although it is hidden :(
And you cannot even see the validator error message because it is hidden

Is there any way around this?

I try to avoid PostBacks to improve the user interface.
I want me to be able to modify .NET javascript to validate controls only when they are visible.

+6
source share
2 answers

I wrote this as a general solution (can be used on all .NET websites).

You only need to add 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, just include the javascript above and add the class OnClientClick="DisableHiddenValidators()" to the submit button:

 <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="DisableHiddenValidators()" /> 

EDIT: The jQuery $(submitButton).click did not work on iPhone / Android. I slightly modified the sample code.

If someone sees something wrong or possible improvements, please comment :)

+9
source

It might also be a good idea to use validation groups in such a situation. If you can group your validators, then select on the button for which you need to check the validation, for which only those validators in the group will be checked. More details here: http://msdn.microsoft.com/en-us/library/vstudio/ms227424(v=vs.100).aspx

0
source

Source: https://habr.com/ru/post/910136/


All Articles