Reputation: 247
Based on an example from MSDN, I'm trying to validate a date range in code-behind, using a RangeValidator
There are three TextBoxes, one for arrival date, departure date, and desired tour date. After clicking a submit button, if the user enters a desired tour date outside the range they specifed in the other two TextBoxes, the RangeValidator's message should appear.
The RangeValidator's min & max values are set in the button's Click event. Its ControlToValidate (the desired tour date) is set in markup.
The problem is: The submit button's Click event does not fire if there is text in any of the first two TextBoxes. If text is entered in any other combination the event fires (though throws an exception obviously).
Markup:
Arrival date:
<br />
<asp:TextBox ID="txtArrival" runat="server"></asp:TextBox>
<br />
Departure date:
<br />
<asp:TextBox ID="txtDeparture" runat="server"></asp:TextBox>
<br />
Tour date:
<br />
<asp:TextBox ID="txtTourDate" runat="server"></asp:TextBox>
<br />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtTourDate"></asp:RangeValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="submit" onclick="btnSubmit_Click"/>
Code-behind::
protected void btnSubmit_Click(object sender, EventArgs e)
{
RangeValidator1.MinimumValue = txtArrival.Text;
RangeValidator1.MaximumValue = txtDeparture.Text;
RangeValidator1.Type = ValidationDataType.Date;
RangeValidator1.Validate();
if (!RangeValidator1.IsValid)
{
RangeValidator1.ErrorMessage = "The tour date must fall between " + txtArrival.Text + " and " + txtDeparture.Text;
}
}
Edit: Thanks for the answer, but it turns out I hadn't set the EnableClientScript attribute of the RangeValidator to "false". New rule - I'm going to wait 30 minutes before asking questions again :)
Upvotes: 0
Views: 1681
Reputation: 1
Hi pls Remove the dipslay="dynamic" and try your code might work as expected:due to this at first click, code behind was getting called, it happens basically if you are using Panel and Telerik control for asynchronous rendering
Upvotes: 0
Reputation: 36
You need to set the RangeValidators min max propertis in the client side. You can call a javascript function OnClientClick of the Submit Button. And you can set the Min Max value of the RangeValidator from here. Like This:
<asp:Button ID="btnSubmit" runat="server" Text="submit" OnClientClick="return SetProperties();" onclick="btnSubmit_Click"/>
<script type="text/javascript">
function SetProperties()
{
var r = document.getElementById("RangeValidator1");
r.MaximumValue = document.getElementById("txtDeparture").value;
r.MinimumValue = document.getElementById("txtArrival").value;
r.ControlToValidate = "txtTourDate";
}
</script>
Upvotes: 1
Reputation: 131
You need to set the min and max values in RangeValidators porperties, it validates the inputs and if no error then enables controls which can then create postbacks.
Upvotes: 2