Using ClientValidationFunction (JavaScript) in an UpdatePanel
I'm trying to determine why my validation function is not being called on my web form. I've read through various articles at MSDN and most notably found this nugget.
When you use the CustomValidator control inside an UpdatePanel control, make sure that the validator control and the control it is associated with are in the same panel. For more information about using the UpdatePanel control for partial-page updates, see Partial-Page Rendering Overview.
With this knowledge I modified my code as follows:
<asp:UpdatePanel ID="UpdatePanel0" runat="server">
<ContentTemplate>
<script type="text/javascript">
function IsNotChecked(obj, args) {
args.IsValid = false;
if (document.getElementByID("cbRegion0").checked)
{
args.IsValid = true; return true;
}
return false;
}
</script>
<asp:CheckBox ID="cbRegion0" runat="server" ValidationGroup="0" AutoPostBack="true" OnCheckedChanged="CheckBox_CheckedChanged" />
<asp:CustomValidator ID="CustomValidator0" runat="server" ValidationG开发者_运维知识库roup="0" ClientValidationFunction="IsNotChecked" ErrorMessage="You did not check the box." ValidateEmptyText="True" />
</ContentTemplate>
</asp:UpdatePanel>
The issue I'm having is that the validation routine does not get executed when clicking the submit button on my page.
Some unique elements of the design is that the code above is actually inside of a .ascx that is added to the page via Control.Add()
but I don't see how that would affect the ClientValidationFunction. I believe it's related to the placement of the <script>
inside the form but despite following directions at MSDN it doesn't seem to have made a difference.
Thanks for any ideas!
Scripts inside of an UpdatePanel will be lost after an async postback. Try putting your IsNotChecked method outside of any update panels... or, implement IScriptControl and put your validation method in the client script file you create to accompany your script control...
I found the answer here at Stack Overflow in the How do I get Client-side validation of ASP.Net page to run? discussion. Sorry for not seeing this earlier. As @Brian pointed out, by specifying the ValidationGroup="0"
in my code that it was expected that the submit button on the page have the same ValidationGroup assigned. In the end I just removed the attribute from the directive and it now calls the JS.
I found the answer because I was looking through the page source and noticed that the submit button was calling a javascript WebForm_OnSubmit()
method which ultimately was checking Page_ValidationActive
.
This led me to the question I've linked.
I hope this helps someone else.
Thanks!
精彩评论