Script Categories













Forms >>> Validation Time.

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.

Time (HH:MM:SS AM/PM format)

Add the below code to the <body> section of your page:

<script language="javascript" type="text/javascript">
/* Visit http://www.yaldex.com/ for full source code
and get more free JavaScript, CSS and DHTML scripts! */
<!-- Begin
function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

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;
}
//  End -->
</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>

JavaScript Editor Get Advanced
JavaScript and Ajax Editor,
Validator and Debugger!

1st JavaScript Editor.



Code was highlighted by 1st JavaScript Editor (The Best JavaScript Editor!).




©