OnClientClick is a useful property introduced in ASP.NET 2.0 that allows us to add some client-side behavior to button control. Using is as simple as providing the script to be called when a button is clicked by a user:
<asp:Button runat="server" ID="Save"
OnClientClick="return confirm('Are you sure?');" />
The problem is that if you use it like that, client-side validation won't fire. Looking at the rendered HTML quickly explains the situation:
onclick="return confirm('Are you sure?');WebForm_DoPostBackWithOptions(...)"
As you can see, the validation doesn't even have a chance to fire (which happens when WebForm_DoPostBackWithOptions is called).
Solving the issue is simple (or not). All that has to be done is a little change in our OnClientClick script (a piece of code found somewhere on the Internet):
<asp:Button runat="server" ID="Save"
OnClientClick="if (!confirm('Are you sure?')) return false;" />
Now we only return false (preventing the submit) in case a user didn't confirm the action, otherwise, the rest of the script will be called thus firing validation.
The reason I said that it may not be a simple issue is the fact, that the validation happens AFTER the confirmation, which is not the best thing in my opinion. Why ask the user about saving his data if there are still errors on the form, of which we will inform him after he confirms that he wants to save it?
After analyzing a bit, the code responsible for dealing with OnClientScript, I have come to a conclusion, that solving this problem is not an easy task. It would require some dirty hacks on the server side to make it pretty or calling validation routines on the client, before displaying the confirmation dialog (keeping in mind that checking if there are validation routines present at all is necessary in this case).
I've just left it as it is. After all it's only a minor inconvenience - at least in my case.