简体   繁体   中英

how to use a asp.net validator with two buttons, but one textbox

i have two asp:LinkButton and one asp:TextBox + one asp:RegularExpressionValidator on my page.

<asp:LinkButton runat="server" ID="lbNearEventSearch" Text="<%# NearEventText %>" OnClick="NearEventSearch_Click" />

<asp:TextBox runat="server" ID="tbEventSearch" onfocus="clearIt(this)" onblur="setIt(this)" CssClass="addontextfield" MaxLength="5" />
<asp:LinkButton runat="server" ID="lbEventSearch" CssClass="addonbutton" OnClick="EventSearch_Click" />
<asp:RegularExpressionValidator runat="server" ID="EventSearchValidator" ControlToValidate="tbEventSearch" Enabled="false" ErrorMessage="<%# ErrorMessageText %>" ValidationExpression="[0-9]{4}" Display="Dynamic" />

i'd like to restrict the validator to only run when the user clicks on the "lbEventSearch" button and do nothing when the other button is clicked.

on pageload there is no way to know witch button was clicked, right? And the onclick callbacks fire after the validator.

All I can think of is disable the validator and enable it inside the onclick callbacks. but I wonder if there would be a better way.

thanks

You can use ValidationGroup for this:

<asp:TextBox runat="server" ID="tbEventSearch" onfocus="clearIt(this)" onblur="setIt(this)" CssClass="addontextfield" MaxLength="5" />
<asp:LinkButton runat="server" ID="lbEventSearch" CssClass="addonbutton" OnClick="EventSearch_Click"
                ValidationGroup="SearchVG" />
<asp:RegularExpressionValidator runat="server" ID="EventSearchValidator" ControlToValidate="tbEventSearch" Enabled="false" ErrorMessage="<%# ErrorMessageText %>" ValidationExpression="[0-9]{4}" Display="Dynamic"
                                ValidationGroup="SearchVG" />

Now only controls with specified group (in this case lbEventSearch ) will trigger validation on the corresponding validators.

只需在lbNearEventSearch上设置CausesValidation="false"

Just give same validationGroup to all elements and lbEventSearch button and dont set validationGroup to other buttons. you can set validation group from property panel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM