Friday, January 11, 2013

OnClientClick breaks validation


PROBLEM: Your validators (RequiredFieldValidator, RangeValidator, RegularExpressionValidator etc) are not being called/fired when you have some client side javascript in OnClientClick that asks a yes/no question e.g. Are you sure you want to delete this?


<asp:Button ID="btnConfirmDelete"
                    runat="server"
                    Text="Delete this Session"
                    ValidationGroup="vgDelete"
                    onclick="btnConfirmDelete_Click"
                    OnClientClick='return confirm("Are you sure you want to delete this session?")' />


SOLUTION:
When the page is rendered, the javascript for the onclick will look something like:


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).

(this guy figured that out: http://vaultofthoughts.net/OnClientClickBreaksValidation.aspx)

Changing it to the below fixes that:

'if (!confirm("Are you sure you want to delete this session?")) return false;'

BUT then you realise that the validators are being called AFTER the prompt (ideally you don't want to prompt the user that they're sure until the last minute after everything is completed). So the this version takes care of that:

'if(Page_ClientValidate()) return confirm("Are you sure you want to delete this session?"); return false;'

Some more info here: http://alvinzc.blogspot.com.au/2006/10/aspnet-requiredfieldvalidator.html

BUT if you're using validation groups, remember to specify it when you call Page_ClientValidate to prevent fields being validated that you don't want validated. Therefore the final version in our case is:

OnClientClick='if(Page_ClientValidate("vgDelete")) return confirm("Are you sure you want to delete this session?"); return false;'

http://techbrij.com/client-side-validation-using-asp-net-validator-controls-from-javascript
http://programmer.webhostingdevelopment.com/index.php/2010/03/specifying-validationgroup-in-page_clientvalidate-function/


No comments:

Post a Comment