PeteEngineer
PeteEngineer

Reputation: 113

Stop Postback if Validation Error

I have the following text box control ;

   <asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
                                OnTextChanged="txtAmount_TextChanged"   ></asp:TextBox>

Here, if there any value change in the text box , txtAmount_TextChanged will be called because AutoPostBack="true" is there in the control.

So if we put a non numeric value in the textbox, validation error will fire from the attribute Class using Jquery, but this error which pops up as a red box from the textbox wont stays for more than 3 seconds, it vanishes when the page posts back within 3 seconds, This post back is happening just because there is a AutopostBack="true".

I cannot do Autopostback="false" because, I need to do some calculation based on this text box value change on the spot.

If I do Autopostback="false", page will not post back and error message stays for ever, but I cannot do any calculations on "txtAmount_TextChanged" event as this event will never be called on textchcange if Autopostback="false".

So, what I do to prevent this postback, if there is any validation error in this textbox?

Upvotes: 1

Views: 7611

Answers (4)

Ruslan
Ruslan

Reputation: 10147

You'll need to add a client-side event handler, and return false from it when you don't want a PostBack to happen.

<asp:TextBox onkeydown="return doMyCheck()" ID="txtAmount" runat="server"
  AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
  OnTextChanged="txtAmount_TextChanged"></asp:TextBox>

JavaScript:

function doMyCheck() {
  if (// call your jQuery validity check) 
    return false;
}

Upvotes: 1

Buzz
Buzz

Reputation: 6330

you can use jquery change function

$('#txtbox').change(function() { if(validationfail){return false;} );


you can use keychange event also

 $('#txtbox').keyup(function() { 
       if(validationfail){return false;} 
    });

Upvotes: 1

Amol Kolekar
Amol Kolekar

Reputation: 2325

Use Input event to check the added text in Textbox using jquery

jQuery('#txtAmount').live('input', function() 
   {
     // do your Validation 
     // If Valid return True
     // If Invalid Return False
   }
) 

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23114

function txtAmount_TextChanged(){
    //do validations here, Eg: validate if txtAmount is valid amount and "> 0"
   return false; //if somethings's wrong, else true

}

Upvotes: 2

Related Questions