Tuesday, November 25, 2008
Using CustomValidator to compare Time Values
ASP.NET ships with many client-side validation controls out of the box, one of them is the Custom Validator control. In client input scenario if you need to compare two date values you can use a CompareValidator and set its Type property to Date, for example check this link. However anytime you need to compare two Time values then there is no support for this in any validation controls.This is how Telerik's TimePicker control looks like.
Fortunately comparing the two values is easy using the CustomValidator control and a little bit of javascript. The CustomValidator control has a ClientValidationFunction property that we can use to trigger a javascript function and using the following function we can can compare two time values.
<script type="text/javascript">
function compareTime(sender, args) {
var start = document.getElementById("<%=rdpStarttime.ClientID %>");
var end = document.getElementById("<%=rdpEndtime.ClientID %>");
var starttime = new Date(0, 0, 0, start.value.substring(11, 13), start.value.substring(14, 16));
var endtime = new Date(0, 0, 0, end.value.substring(11, 13), end.value.substring(14, 16));
args.IsValid = (endtime >= starttime);
}
</script>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="End time should be greater than Start" ClientValidationFunction="compareTime" ControlToValidate="rdpEndtime"></asp:CustomValidator>
Here's how it looks like.
Labels: ASP.NET, CustomValidator, Validation
<< Home