Tuesday, November 20, 2012

JAVA SCRIPT TO VALIDATE TIME IN "dd-mm-yyyy hh:mm:ss" FORMAT


function validateStartTime() {
//This function will validte the datetimes of this format : dd-mm-yyyy hh:mm:ss
var date = document.getElementById("startTime").value.trim();
    var valid = true;
    var spaceIndex = date.indexOf(" ");
    var onlyDate = date.substring(0,spaceIndex);
    var dateData = onlyDate.split("-");
    var onlyTime = date.substring(spaceIndex);
    var timeData = onlyTime.split(":");
    var day = (dateData[0]);    
    var month = (dateData[1]);   
    var year   = (dateData[2]);   
    var hour   = (timeData[0]);   
    var min = (timeData[1]);   
    var sec = (timeData[2]);     
    var regForDate = new RegExp("\\d{1,2}-\\d{1,2}-\\d{4}$");
    var regForTime = new RegExp("\\d{1,2}:\\d{1,2}:\\d{1,2}$");
 
    if(!regForDate.test(onlyDate)) valid =false;
    else if(!regForTime.test(onlyTime)) valid =false;
    else if((month < 1) || (month > 12)) valid = false;
    else if((day < 1) || (day > 31)) valid = false;
    else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;
    else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;
    else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;
    else if((hour < 0) || (hour > 24)) valid = false;
    else if((min < 0) || (min > 59)) valid = false;
    else if((sec < 0) || (sec > 59)) valid = false;      

return valid;
}

No comments:

Post a Comment