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.

 

ScreenHunter_02 Nov. 25 12.57

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.


 ScreenHunter_03 Nov. 25 12.16

Labels: , ,


Comments:
I have write the above code and given end time is lesser than start time but the data entering into database. please anybody help me
 
I would check for Page.IsValid in codebehind and make sure that ValidationGroup is set on the submit button
 
This s not working properly.. some problem is there..pls give an exact solution for this problem
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?