Reputation: 567
I want to set a Range Validator on a text box to prevent someone from ordering more of a product than is available. I have the amount available stored in a database and I databound the maximum value property of the Ranged Validator to the field in the database.
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="tbQuantity" Display="Dynamic" ErrorMessage = "Can't Order More Than Quantity."
ForeColor="Red" MaximumValue='<%# Eval("Quantity") %>' MinimumValue="0"></asp:RangeValidator>
However when I debug the program I get some unexpected results.
The quantity is 17. and 1 does not trigger the error message, but 2-9 does and 10-17 doesn't trigger it but 18 and up do. I'm guessing this has something to do with the fact that it is comparing strings but I'm not sure how to change it to comparing numbers.
Upvotes: 6
Views: 8106
Reputation: 374
protected void RangeValidator5_Init(object sender, EventArgs e)
{
((RangeValidator)sender).MaximumValue = DateTime.Today.ToString("yyyy/MM/dd");
((RangeValidator)sender).MinimumValue = DateTime.Today.AddYears(-100).ToString("yyyy/MM/dd");
}
Upvotes: 0
Reputation: 27405
The default range validator type is string, change the Type
property to Integer
<asp:RangeValidator
ID="RangeValidator1" runat="server"
ControlToValidate="tbQuantity"
Display="Dynamic"
ErrorMessage="Can't Order More Than Quantity."
ForeColor="Red"
MaximumValue='<%# Eval("Quantity") %>'
MinimumValue="0"
Type="Integer" /> // <-- add type property of integer
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basecomparevalidator.type.aspx
Upvotes: 5
Reputation: 28520
Have you tried setting the type attribute to integer?
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="tbQuantity" Display="Dynamic"
ErrorMessage="Can't Order More Than Quantity."
ForeColor="Red" MaximumValue='<%# Eval("Quantity") %>'
MinimumValue="0" Type="Integer">
</asp:RangeValidator>
More information can be found here (don't let the title BaseCompareValidator in the title throw you, Type is a valid property for the RangeValidator
control):
BaseCompareValidator.Type Property
Upvotes: 3