Given:
<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" />开发者_如何学C;
<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>
How do I make it so that the validator for the stock count wont run unless the limited stock checkbox is checked?
Use a CustomValidator instead. See the section on Client Side Validation at the bottom of this page: http://msdn.microsoft.com/en-us/library/f5db6z8k%28VS.71%29.aspx
You can use a script that checks the value of the checkbox and performs your validation.
<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>
You could set AutoPostBack to true on the checkbox and then in the checkbox event you could enable/disbale the required field validator.
In the aspx page set the AutoPostBack property of the checkbox
<asp:CheckBox ID="limitedStock" runat="server" AutoPostBack="True" />
In the CheckChanged event of the checkbox you just set the Enabled property of the RequiredFieldValidator as required:
RequiredFieldValidator2.Enabled = limitedStock.Checked;
James :-)
精彩评论