Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop postback on TextChanged

I have a textbox in an aspx page that has a TextChanged event attached to it. I also have a validator attached to the textbox.

When the text is changed, the validate triggers but in case there is an error the textchanged event is still called. Do you know if it's possible to stop the postback on textchanged if the validator fires?

<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqQuantity" ControlToValidate="txtQuantity" runat="server" ErrorMessage="The quantity is mandatory."></asp:RequiredFieldValidator>
like image 573
Dante Avatar asked Oct 06 '09 09:10

Dante


2 Answers

You can move validation to client side adding EnableClientScript="true" attribute. Postback won't occur as check will be performed with JS.

Other than that you can check whether page is valid when performing callback function for TextChanged event so that to define whether function can proceed. You should add ValidationGroup attribute to your validator and call Page.Validate function specifying that group before Page.IsValid is checked.

Upd

Here's the tip.

Add your own JS function, e.g.:

function IsValid( args ) {
        if( args.value.length == 0 ) {
            return false;
        }
        else {
            return true;
        }
    }

In Page_Load event add this code:

txtQuantity.Attributes[ "onchange" ] = "if ( IsValid(this) == false ) return;";

This won't mess up auto postback when input is correct, but will prevent postback otherwise.

like image 179
terR0Q Avatar answered Sep 20 '22 06:09

terR0Q


Add CausesValidation="true" for the text box and it will be good. If the validation is not valid there won't be any post-back.

<asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged" CausesValidation="true"></asp:TextBox>

like image 34
Naveen Avatar answered Sep 18 '22 06:09

Naveen