ASP.NET c#仅在选中复选框时验证表单的一部分

时间:2010-08-25 09:53:27

标签: c# asp.net validation

假设:

    <div class="subHead">Stock Options</div>
    <table class="settingTable">
        <tr>
            <td colspan="2"><b>Limited Stock</b></td>
        </tr>
        <tr>
            <td width="50" align="center"><asp:CheckBox ID="limitedStock" runat="server" /></td>
            <td>If checked this product will have a limited stock</td>
        </tr>
    </table>
    <table class="settingTable">
        <tr>
            <td colspan="2"><b>Stock Count</b></td>
        </tr>
        <tr>
            <td>
                <asp:TextBox ID="stockCount" runat="server" CssClass="tbox"></asp:TextBox>
                <asp:RequiredFieldValidator runat="server"
                          id="RequiredFieldValidator2"
                          ControlToValidate="stockCount"
                          ErrorMessage="You need to enter a value"
                          display="Dynamic" />
                <asp:RangeValidator runat="server"
                    id="rangeVal1"
                    MinimumValue="0" MaximumValue="999999999999"                        
                    ControlToValidate="stockCount"
                    ErrorMessage="Enter a numeric value of at least 0"
                    display="Dynamic" />
            </td>
        </tr>
    </table>

除非选中限量股票复选框,否则如何使股票计数的验证器不会运行?

2 个答案:

答案 0 :(得分:3)

请改用CustomValidator。请参阅本页底部的“客户端验证”部分:http://msdn.microsoft.com/en-us/library/f5db6z8k%28VS.71%29.aspx

您可以使用检查复选框值的脚本并执行验证。

<script language="text/javascript">
    function validateStockCount(oSrc, args){
       //Use JQuery to look for the checked checkbox and only if it is found, validate
       if($('.limitedStock:checked') == undefined) {
           args.IsValid = true;
       }
       else {
           args.IsValid = (args.Value.length >= 0) && (args.Value.length <= 999999999999);

       }
    }
</script>

<asp:CheckBox ID="limitedStock" runat="server" CssClass="limitedStock" />

<asp:TextBox ID="stockCount" runat="server" CssClass="tbox"></asp:TextBox>

<asp:CustomValidator id="CustomValidator1" runat=server 
   ControlToValidate = "stockCount"
   ErrorMessage = "You need to enter a numeric value of at least 0!"
   ClientValidationFunction="validateStockCount" >
</asp:CustomValidator>

答案 1 :(得分:2)

您可以在复选框上将AutoPostBack设置为true,然后在复选框事件中,您可以启用/取消所需的字段验证程序。

在aspx页面中设置复选框的AutoPostBack属性

<asp:CheckBox ID="limitedStock" runat="server" AutoPostBack="True" /> 

在复选框的CheckChanged事件中,您只需根据需要设置RequiredFieldValidator的Enabled属性:

RequiredFieldValidator2.Enabled = limitedStock.Checked;

詹姆斯: - )