Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validate time properly

Status
Not open for further replies.

CHRISWYA

IS-IT--Management
Sep 14, 2004
19
GB
i am using the following code to validate a time field in my application, however this only checks the correct characters are used and not in the correct order. Ideally i require validation that checks that the data entered is in the following order HH:MI, any suggestions appreciated


var checkOK = "0123456789:";
var checkStr = theForm.p_open_time.value;
var allValid = true;
var allNum = "";
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
alert("Please enter a time in the format HH:MI.");
theForm.p_open_time.focus();
return false;
}
return true;
 

i require validation that checks that the data entered is in the following order HH:MI

Given that both HH and MM are numeric fields with a maximum length of 2 digits, how can we possibly know if the user has entered HH before MM or not?

We can test for digit(s), colon, digit(s), and can test for HH and MM values out-of-range, but there is no way of knowing if the user has entered MM:HH or HH:MM.

Hope this helps,
Dan
 
Sorry - I should have said - maybe you would be better off with HH and MM drop-downs, with values from 1-12 (or 0-24), and 0-59 - that way, there could be no mistaking which values were for which component (HH or MM).

Hope this helps,
Dan
 
found and adjusted a solution...

<script 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.Format required is HH:MI");
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 24.");
document.LogForm.p_open_time.focus()
return false;
}

if (hour > 12 && ampm != null) {
alert("You cant specify AM or PM for military time.");
document.LogForm.p_open_time.focus()
return false;
}
if (minute<0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
document.LogForm.p_open_time.focus()
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
document.LogForm.p_open_time.focus()
return false;
}
return false;
}
</script>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top