|
↑
Forms >>>
This function verifies that a string is a valid time, in the form hh:mm:ss am/pm, where seconds are optional. It accepts military time (hour between 0 and 23) as long as am/pm isn't specified. It requires am/pm when the hour is less than or equal to 12.
Add the below code to the <body> section of your page:
<script
language="javascript"
type="text/javascript">
function
IsValidTime(timeStr)
{
var
timePat =
/^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
var
matchArray =
timeStr.match(timePat);
if
(matchArray
==
null)
{
alert("Time
is not in a valid format.");
return
false;
}
hour
=
matchArray[1];
minute
=
matchArray[2];
second
=
matchArray[4];
ampm
=
matchArray[6];
if
(second=="")
{
second =
null;
}
if
(ampm=="")
{
ampm =
null
}
if
(hour
<
0
||
hour >
23)
{
alert("Hour
must be between 1 and 12. (or 0 and 23 for military time)");
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.");
return
false;
}
}
if
(hour
>
12
&&
ampm !=
null)
{
alert("You
can't specify AM or PM for military time.");
return
false;
}
if
(minute<0
||
minute >
59)
{
alert
("Minute
must be between 0 and 59.");
return
false;
}
if
(second
!=
null
&&
(second
<
0
||
second >
59))
{
alert
("Second
must be between 0 and 59.");
return
false;
}
return
false;
}
</script>
<form
name=timeform
onSubmit="return
IsValidTime(document.timeform.time.value);">
Time (HH:MM:SS AM/PM format)
<input
type=text
name=time><br>
<input
type="submit"
value="Submit">
</form>
|
→
|