views:

239

answers:

5

I have some validation JS code on client, that must be executed befor PostBack. If this validation code return 'false', postback is needless. How it can be disabled?

+1  A: 

Set the OnClientClick='YourJSValidationFunction' on your ASP button.

Then have the YourJSValidationFunction return true or false.

False will prevent postback

Example: http://vijaymodi.wordpress.com/2007/06/08/button-onclick-and-onclientclick-2/

Ed B
+3  A: 

Remember that the real validation should always happen on the server. Anything you do client-side is merely an optimization to save a few http round trips.

The easiest way to keep your client side and server-side validation in sync with ASP.Net is to use the validation controls. The validation controls will do both client side and server side validation, in such a way that if validation fails on the client it never posts to the server.

If you want to do something that's not covered by the standard validation controls, you should either use a CustomValidator or inherit your own control from BaseValidator.

Joel Coehoorn
A: 

What do you use: some validator or some button with onclick event? If you have

<input type="button" id="btnID" runat="server" onclick="CheckValid();"/>

function CheckValid()
{
   if(!IsValid) return false;//then no post back occer
}
Kate
+1  A: 

If the postback is being triggered by a button then you can do something like this:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return IsValid();" />

If the IsValid function returns false then the postback will be prevented. If you want to catch all postbacks regardless of which control triggers it then you can use
<form id="form1" runat="server" onsubmit="return IsValid();">

A: 

Depending on the validation you're attempting, you may also be able to use the CustomValidator control. This would also allow you to easily implement your validation logic on the server side.

AaronSieb