Search code examples
sharepointsharepoint-2010sharepoint-2007

How to validate & compare hours part of sharepoint datetime control?


I have two sharepoint datetime controls where timeOnly=true. I need to validate as required field & validate as one controls Hours value must be Greater than & Equal to other one. I want to do it in Client side.

Note: Using timeOnly="true" means need to validate Hours & minutes Only.


Solution

  • Created an asp.net custom validator to compare hours & minutes part of two datetime controls.
    And called javascript function from ClientValidationFunction property of asp.net custom validator.
    Function is here:

            function ValidateHour&Minute(sender, args){
                var startDateHour = document.getElementById("<%=DateTimeControlStartDate.Controls[1].ClientID %>").value;// gets value from hours dropdown list for 1st datetime control
                var startDateMinute = document.getElementById("<%=DateTimeControlStartDate.Controls[2].ClientID %>").value;// gets value from minutes dropdown list for 1st datetime control
                var timeStart = new Date();
                var timeEnd = new Date();
                var strStartHour;
                var hourType;
                hourType = startDateHour.split(' '); 
                if (hourType[1] == "AM") {
                    startDateHour=startDateHour.split(' ');
                    strStartHour = startDateHour[0];
                }
                else {
                    startDateHour=startDateHour.split(' '); 
                    strStartHour = startDateHour[0]; 
                    strStartHour = parseInt(strStartHour) + 12; 
                }
                timeStart.setHours(strStartHour, startDateMinute, 0, 0); 
                var strEndHour;
                var endDateHour = document.getElementById("<%=DateTimeControlEndDate.Controls[1].ClientID %>").value;// gets value from hours dropdown list for 2nd datetime control
                var endDateMinute = document.getElementById("<%=DateTimeControlEndDate.Controls[2].ClientID %>").value;// gets value from minutes dropdown list for 2nd datetime control
                hourType = endDateHour.split(' ');
                if (hourType[1] == "AM") {
                    endDateHour=endDateHour.split(' ');
                    strEndHour = endDateHour[0]; 
                }
                else {
                    endDateHour= endDateHour.split(' ');
                    strEndHour = endDateHour[0]; 
                    strEndHour = parseInt(strEndHour) + 12; 
                }
                timeEnd.setHours(strEndHour, endDateMinute, 0, 0);
                if (timeStart < timeEnd) {
                    args.IsValid = true;
    
                }
                else {
                    args.IsValid = false;
                }
            }