Stop postback in TextChanged

I have a text box on an aspx page with a TextChanged event attached to it. I also have a validator attached to a text box.

When the text is changed, the validation triggers, but if an error occurs, the textchanged event is still raised. Do you know if it is possible to stop the postback when changing the text if the validator works?

<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>
+3
source share
4 answers

You can transfer the check to the client side with the addition of an attribute EnableClientScript="true". Rollback will not occur, as verification is performed using JS.

, TextChanged, , . ValidationGroup Page.Validate, , Page.IsValid .

Upd

.

JS, :

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

Page_Load :

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

, .

+3

CausesValidation="true" , . , .

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

+3

try after changing AutoPostBack = "true" as AutoPostBack = "false" ..

0
source

Just share the inline, shorter version of the accepted answer:

<asp:TextBox ID="txtQuantity" runat="server"
    AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"
    onchange="if (this.value.length == 0) return;"></asp:TextBox>

Having the same issue with RequiredFieldValidator, the above worked for me.

Famous nag: the designer complains that "onchange" is not a valid attribute on the server side.

0
source

Source: https://habr.com/ru/post/1719365/


All Articles