忽略.NET验证,如果元素是隐藏的(显示:无) [英] Ignore .NET validators if element is hidden (display: none)
问题描述
我们经常接触到的.NET验证问题上正在使用的JavaScript / CSS的隐藏要素(如显示:无)
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>
用JavaScript:
with JavaScript:
$('#chkNewsletter').changed(function() {
$(this).is(':checked') ? $('#newsletterOnly').show() : $('#newsletterOnly').hide();
});
它不应该验证的 txtEmail 的,如果它是隐藏的。结果
你不能提交表单,如果的 newsletterOnly 的是隐藏的,因为尽管它已经被隐藏的RequiredFieldValidator仍然有效:(结果
你甚至不能看到验证错误消息,因为它隐藏
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?
我试图避免回传给改善用户体验。结果
我希望我可以修改.NET JavaScript来验证时,才可见。
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.
推荐答案
我写了这是一个通用的解决方案(可在所有.NET网站上使用)。
I wrote this as a general solution (can be used on all .NET websites).
您只需要一个的OnClientClick添加到提交按钮。
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();
}
要使用它,只需包括上述JavaScript和添加类的OnClientClick =DisableHiddenValidators()
来提交按钮:
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()" />
编辑:
jQuery的 $(提交按钮)。单击
函数没有在iPhone / Android的工作。我已经改变略高于样品code。
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 :)
这篇关于忽略.NET验证,如果元素是隐藏的(显示:无)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!