jump to navigation

OnClientClick Breaks Validation August 20, 2009

Posted by codinglifestyle in ASP.NET, Javascript.

It’s a horrible sinking feeling when you make a sizable change and everything goes tits up.  I was updating an ASP.NET form the other day which had a lot of HTML controls on it.  I decided to update these to ASP.NET controls and replaced a number of buttons.  While doing this I cleaned up the onclick code, which I placed in OnClientClick.  Unwittingly I managed to break validation for the entire page, as just about every button used this attribute.  I won’t bore you with the details, but suffice it to say I had a few red herrings and couldn’t understand why my page’s validators suddenly stopped working.  I spent all night fretting about it, but this morning the first thing I did was drop a new button on the page, load it up, and click it.  Presto, validation worked for that button but not the other buttons on the page.  What’s going on?

<asp:Button runat=”server” ID=”Save” OnClientClick=”return confirm(‘Are you sure?’);” /> 

 It becomes crystal clear when you view the source of the page.  We will see something like this:

onclick=”return confirm(‘Are you sure?’);WebForm_DoPostBackWithOptions(…)”

It is now clear that we are returning before the validator’s script has a chance to run.  I will pause now for an, “Ohhhhhhh….  <slap to head>”.

Typically, we want to stop execution if our called function returns false but continue if it returns true.  Solving this problem requires just a small change to our script.  Take a look below:

onclick=”if (!confirm(‘Are you sure?’)) return false; WebForm_DoPostBackWithOptions(…)”

Now we will only return false if our script returns false.  If our script returns true, the browser will continue to call WebForm_DoPostBackWithOptions(…) which will execute our validators.

ref: http://vaultofthoughts.net/OnClientClickBreaksValidation.aspx


1. Yazan - March 6, 2011

call Page_ClientValidate(); in your javascript to validate all your validators in client side.

May this helps

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: