页面上有多个必填字段验证器,但它们需要应用于不同的按钮单击

时间:2010-10-13 13:28:26

标签: asp.net multiple-instances requiredfieldvalidator

我正在开发asp.net页面,我有以下情况:

我有2个字段需要fieldvalidvalidator,当点击button1时需要“激活”他们的验证,但是当点击button2时不需要“触发”验证,而另一个字段由另一个具有相反情况的requiredfieldvalidator验证。 (当点击button2时,此字段的requiredfieldvalidator需要“触发”,但是当点击button1时则不需要“触发”。)对于最简单的解决方案的任何建议都将不胜感激。

提前致谢

2 个答案:

答案 0 :(得分:8)

您可以使用Validation Group

示例代码:

<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>

答案 1 :(得分:3)

使用验证组。请参阅下一篇文章http://www.dotnet-guide.com/validationgroups.html