Monday, July 7, 2008

ValidTime JS

function isValidTime(timeStr, timeValue)
{
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AMamPMpm))?$/;
var matchArray = timeStr.match(timePat);
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];
if (matchArray == null)
{
alert("Time is not in a valid format.");
timeValue.select();
timeValue.focus();
return false;
}
if (second=="")
{
second = null;
}
if (ampm=="")
{
ampm = null
}
if (hour <> 23)
{
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
timeValue.select();
timeValue.focus();
return false;
}
if (hour <= 12 && ampm == null)
{
if (confirm("Please indicate which time format you are using. OK = Standard Time, CANCEL = Military Time"))
{
alert("You must specify AM or PM.");
timeValue.select();
timeValue.focus();
return false;
}
}
if (hour > 12 && ampm != null)
{
alert("You can't specify AM or PM for military time.");
timeValue.select();
timeValue.focus();
return false;
}
if (minute<0> 59)
{
alert ("Minute must be between 0 and 59.");
timeValue.select();
timeValue.focus();
return false;
}
if (second != null && (second <> 59))
{
alert ("Second must be between 0 and 59.");
timeValue.select();
timeValue.focus();
return false;
}
return true;
}

No comments: