Stop postback on TextChanged

岁酱吖の 提交于 2019-12-01 07:04:16

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.

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>

try it after change AutoPostBack="true" as AutoPostBack="false"..

Just sharing an 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 problem with a RequiredFieldValidator, the above worked for me.

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

What I do is in my client validation function I test the event type I am in. If the event shows me in a change event, I claim the validation passed and leave.

		if (event.type === 'change') {
			args.IsValid.true;
      return;
		}

I believe this is the best solution as you can leave the validator wired up and the textbox set as you like and no longer worry about the change event causing the validation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!