Is Valid Time
This JavaScript function will check to see if the passed-in time is valid. The format can be hh:mm or hh:mm:ss and the hour part can be military time (0-23) or meridian format (1-12 with AM/PM at the end). It will return true if the time is valid. Next week we'll look at this same function but use regular expressions to shorten it quite a bit. function isValidTime(value) {
var colonCount = 0;
var hasMeridian = false;
for (var i=0; i<value.length; i++) {
var ch = value.substring(i, i+1);
if ( (ch < '0') || (ch > '9') ) {
if ( (ch != ':') && (ch != ' ') && (ch != 'a') && (ch != 'A') && (ch != 'p') && (ch != 'P') && (ch != 'm') && (ch != 'M')) {
return false;
}
}
if (ch == ':') { colonCount++; }
if ( (ch == 'p') || (ch == 'P') || (ch == 'a') || (ch == 'A') ) { hasMeridian = true; }
}
if ( (colonCount < 1) || (colonCount > 2) ) { return false; }
var hh = value.substring(0, value.indexOf(":"));
if ( (parseFloat(hh) < 0) || (parseFloat(hh) > 23) ) { return false; }
if (hasMeridian) {
if ( (parseFloat(hh) < 1) || (parseFloat(hh) > 12) ) { return false; }
}
if (colonCount == 2) {
var mm = value.substring(value.indexOf(":")+1, value.lastIndexOf(":"));
} else {
var mm = value.substring(value.indexOf(":")+1, value.length);
}
if ( (parseFloat(mm) < 0) || (parseFloat(mm) > 59) ) { return false; }
if (colonCount == 2) {
var ss = value.substring(value.lastIndexOf(":")+1, value.length);
} else {
var ss = "00";
}
if ( (parseFloat(ss) < 0) || (parseFloat(ss) > 59) ) { return false; }
return true;
}
The first thing the function does is go through all the characters in the value. If any character is invalid, then we're done. It also counts the number of colons while going through, and if an "a" or "p" (either upper case or lower case) is found, then we set some flags for meridian and optionally PM.
Once all the characters are evaluated, the number of colons is looked at. This has to be either 1 or 2. Then things are split up based on the colons. The numbers before the first colon must be in a valid range (0-23, or 1-12 if AM/PM was included). The numbers between the first and second colon (or after the 1st colon if there's only 1) must be between 0 and 59. If there were 2 colons, then the numbers after the 2nd colon must be between 0 and 59. If all those checks pass, then the string is a valid time and true is returned.