Multiple RequiredFieldValidators on page but they need to apply to different button clicks

不羁岁月 提交于 2020-01-29 13:35:31

问题


I'm working on a asp.net page and I have the following scenario:

I have 2 fields that have requiredfieldvalidators which need to "fire" their validation when button1 is clicked but NOT when button2 is clicked and another field which is validated by another requiredfieldvalidator with the opposite scenario. (requiredfieldvalidator for this field needs to "fire" when button2 is clicked but NOT when button1 is clicked.) Any suggestions for the simplest solution would be appreciated.

Thanks in advance


回答1:


You can use Validation Group.

Sample code here:

<body>
    <form id="form1" runat="server">
    <div>
        <h1>Group1</h1>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1" ValidationGroup="group1"></asp:RequiredFieldValidator>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox2" ValidationGroup="group1"></asp:RequiredFieldValidator>

        <br /><br />
        <h1>Group2</h1>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox3" ValidationGroup="group2"></asp:RequiredFieldValidator>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox4" ValidationGroup="group2"></asp:RequiredFieldValidator>

        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="group1" />
        <asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="group2" />
    </div>
    </form>
</body>



回答2:


Use validation groups. See the next article http://www.dotnet-guide.com/validationgroups.html.



来源:https://stackoverflow.com/questions/3924186/multiple-requiredfieldvalidators-on-page-but-they-need-to-apply-to-different-but

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