I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.
How can this be accomplished? Ive included a sample of my current code below.
sample.aspx
<asp:textbox id=foo runat=server />
<asp:requiredfieldvalidator id=val runat=server controltovalidate=foo />
<asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') />
sample.aspx.vb
Sub Page_Load()
If Page.IsPostback() Then
Page.Validate()
If Page.IsValid Then
'process page here'
End If
End If
End Sub
Thanks for any help.
This seems to be a very common problem.
The workaround:
Validate the page first, then call confirm, as shown here and here.
This does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit onclick.
How to make this work properly, i.e. Validate the page first (and only once), then show the confirm box, I do not yet know.
Edit: Here's a useful suggestion:
What ASP.NET does behind the scenes when validation controls exist, is add an autogenerated onClick event for each button. This OnClick event would supercede the custom OnClick event. So to overcome this I did the following:
- add CausesValidation = False
- added Validate() and IsValid code to the onClick event behind the page to simulate the now missing autogenerated validation code behind the button.
Edit 2: A complete example
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}" CausesValidation="false" />
<asp:Button ID="btnSave" runat="server" OnClientClick="javascript:return ConfirmSubmit()" OnClick="btnSave_Click" Text="Save" />
//---javascript -----
function ConfirmSubmit()
{
Page_ClientValidate();
if(Page_IsValid) {
return confirm('Are you sure?');
}
return Page_IsValid;
}
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