473,769 Members | 6,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

MAJOR headache with Time Validation Script

Hello,

I'm having some serious problems debugging a script that I'm trying to make
work. I'm working on a form where a user can type in a time (in the format
of HH:MM), and another script automatically calculate how much time is
inbetween.

That part of it is working fine, but what ISN'T working fine is the script
that validates whether or not the user has entered the time in proper
syntax, and to make sure that the Time In does not come after the Time Out.

Here's the two functions, one to validate In and one to validate Out:
function validateInTimeF ormat(){
// This function validates whether or not a user has entered proper time
into the form
var inTime = document.frm.in Time.value;

if (validatingOutT ime == false) {
if (inTime.indexOf (":") == "-1"){
alert("Time In: You didn't put a \":\"");
this.document.f rm.inTime.focus ();
validatingInTim e = true;
return false;
} else if ((inTime.substr (0,inTime.index Of(":"))<1) ||
(inTime.substr( 0,inTime.indexO f(":"))>12)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.in Time.focus();
validatingInTim e = true;
return false;
} else if ((inTime.substr (inTime.indexOf (":")+1,inTime. length) < 0) ||
(inTime.substr( inTime.indexOf( ":")+1,inTime.l ength) > 59)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.in Time.focus();
validatingInTim e = true;
return false;
} else {
validatingInTim e = false;
return true;
}

}
}

function validateOutTime Format(){
// This function validates whether or not a user has entered proper time
into the form
var outTime = document.frm.ou tTime.value;

if (validatingInTi me == false) {
if (outTime.indexO f(":") == "-1"){
alert("Time In: You didn't put a \":\"");
this.document.f rm.outTime.focu s();
validatingOutTi me = true;
return false;
} else if ((outTime.subst r(0,outTime.ind exOf(":"))<1) ||
(outTime.substr (0,outTime.inde xOf(":"))>12)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.ou tTime.focus();
validatingOutTi me = true;
return false;
} else if ((outTime.subst r(outTime.index Of(":")+1,outTi me.length) < 0) ||
(outTime.substr (outTime.indexO f(":")+1,outTim e.length) > 59)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.ou tTime.focus();
validatingOutTi me = true;
return false;
} else {
validatingOutTi me = false;
return true;
}

}
}

Here's how i have it called in the page:

<br />Time: In &nbsp;<input name="inTime" type="text"
class="formInpu tText" id="inTime" size="5" onblur="return
validateInTimeF ormat();" />
<select name="inTime12H r" class="formInpu tText" id="inTime12Hr" >
<option value="AM">AM</option>
<option value="PM">PM</option>
</select><br />
Time: Out <input name="outTime" type="text" class="formInpu tText"
id="outTime" size="5" onblur="return validateOutTime Format();" />
<select name="outTime12 Hr" class="formInpu tText" id="outTime12Hr ">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
FYI: I know I haven't done anything in the functions with the AM and PM.
Eventually I'll just have it add 12 hours to the result if it's PM, but I
haven't reached that point yet. I've been working in IE and also in Mozilla
Firefox (with the JavaScript Debugger). I get everything from "Error:
outTime has no properties" to some crazy nsexception type stuff in Mozilla.
I think the latter occurs when trying to focus the cursor back on the field
in question. It (somewhat) works in IE but not in Mozilla at all. Also,
noting the "if validatingInTim e==false" stuff, I had to do that because it
would automatically jump between the inTime field and outTiem field into
eternity if you clicked on one and then the other. Any clues on how much
I've screwed this up? JavaScript is SOOOOOOOOOOO difficult to debug.

Thanks in advance,
Kenneth
Jul 20 '05 #1
6 2518
Kenneth wrote:
Hello,

I'm having some serious problems debugging a script that I'm trying to make
work. I'm working on a form where a user can type in a time (in the format
of HH:MM), and another script automatically calculate how much time is
inbetween.


Instead of trying to read what you are doing, here is a more elegant way
of doing things... use regular expressions. I whipped up something
quickly, but I think it works perfectly. In this example, the function
will validate that the time is between 0:00 and 23:59, military time.
It is a simple exercise to change it to AM/PM, if you need to.

I hope this helps
Brian

/////////////////////////////////////////////////////////////////////////
// validate the time is between 0:00 and 23:59.
// input : time -- string value to validate
function validateTime(ti me)
{
// delcare the variables
var hours = -1;
var mins = -1;

// Here is a regExp that makes sure the time is in the form of
// 0:00 to 29:59... of course, we will need to make sure that
// it is less than 24 later
valid_time = /([0-2]?[0-9]):([0-5][0-9])/

// Run the regular expression
time_tokens = time.match(vali d_time);

// If the match was successful, time_tokens will not be null,
// and the first element will be an exact match of the value
if( time_tokens && time_tokens[0] == time)
{
// The values will be in the time_tokens object
hours = time_tokens[1];
mins = time_tokens[2];

// Check to make sure the hours value is not
//greater than 23
if(hours >= 24)
hours = -1;
}

// See if we have good values. If they are good, then you
//are successful
if(hours >= 0 && mins >= 0)
alert("VALID: " + hours + " hours and " + mins + " minutes");
else
alert("INVALID TIME: Must be HH:MM");
}

Jul 20 '05 #2
Brian Genisio wrote:
Kenneth wrote:
Hello,

I'm having some serious problems debugging a script that I'm trying to
make
work. I'm working on a form where a user can type in a time (in the
format
of HH:MM), and another script automatically calculate how much time is
inbetween.

Instead of trying to read what you are doing, here is a more elegant way
of doing things... use regular expressions. I whipped up something
quickly, but I think it works perfectly. In this example, the function
will validate that the time is between 0:00 and 23:59, military time. It
is a simple exercise to change it to AM/PM, if you need to.

I hope this helps
Brian

/////////////////////////////////////////////////////////////////////////
// validate the time is between 0:00 and 23:59.
// input : time -- string value to validate
function validateTime(ti me)
{
// delcare the variables
var hours = -1;
var mins = -1;

// Here is a regExp that makes sure the time is in the form of
// 0:00 to 29:59... of course, we will need to make sure that
// it is less than 24 later
valid_time = /([0-2]?[0-9]):([0-5][0-9])/

// Run the regular expression
time_tokens = time.match(vali d_time);

// If the match was successful, time_tokens will not be null,
// and the first element will be an exact match of the value
if( time_tokens && time_tokens[0] == time)
{
// The values will be in the time_tokens object
hours = time_tokens[1];
mins = time_tokens[2];

// Check to make sure the hours value is not
//greater than 23
if(hours >= 24)
hours = -1;
}

// See if we have good values. If they are good, then you
//are successful
if(hours >= 0 && mins >= 0)
alert("VALID: " + hours + " hours and " + mins + " minutes");
else
alert("INVALID TIME: Must be HH:MM");
}


I've got it /almost/ working. Thanks for the help, that really cleans
the code up.

I'm getting errors such as this now:
Error: [Exception... "'Permissio n denied to get property
XULElement.sele ctedIndex' when calling method:
[nsIAutoComplete Popup::selected Index]" nsresult: "0x8057001e
(NS_ERROR_XPC_J S_THREW_STRING) " location: "JS frame :: ... etc.

Obviously I don't want my code breaking Mozilla...

All I'm trying to do now is set the focus on the proper time element.
I'm trying to do this by feeding the element name into the function
(i.e. validateTimeFor mat('timeIn',th is.value);)

However, when I'm setting the focus, I must be using the wrong syntax.
I'm not all that familiar with JavaScript, obviously. This is how I'm
doing it (where timeType is equal to the 'timeIn' that I passed in the
function): document.frm[timeType].focus();

Thoughts?

Thanks in advance, and thanks for the help.

Ken
Jul 20 '05 #3
Brian Genisio wrote:
Kenneth wrote:
Hello,

I'm having some serious problems debugging a script that I'm trying to
make
work. I'm working on a form where a user can type in a time (in the
format
of HH:MM), and another script automatically calculate how much time is
inbetween.

Instead of trying to read what you are doing, here is a more elegant way
of doing things... use regular expressions. I whipped up something
quickly, but I think it works perfectly. In this example, the function
will validate that the time is between 0:00 and 23:59, military time. It
is a simple exercise to change it to AM/PM, if you need to.

I hope this helps
Brian

/////////////////////////////////////////////////////////////////////////
// validate the time is between 0:00 and 23:59.
// input : time -- string value to validate
function validateTime(ti me)
{
// delcare the variables
var hours = -1;
var mins = -1;

// Here is a regExp that makes sure the time is in the form of
// 0:00 to 29:59... of course, we will need to make sure that
// it is less than 24 later
valid_time = /([0-2]?[0-9]):([0-5][0-9])/

// Run the regular expression
time_tokens = time.match(vali d_time);

// If the match was successful, time_tokens will not be null,
// and the first element will be an exact match of the value
if( time_tokens && time_tokens[0] == time)
{
// The values will be in the time_tokens object
hours = time_tokens[1];
mins = time_tokens[2];

// Check to make sure the hours value is not
//greater than 23
if(hours >= 24)
hours = -1;
}

// See if we have good values. If they are good, then you
//are successful
if(hours >= 0 && mins >= 0)
alert("VALID: " + hours + " hours and " + mins + " minutes");
else
alert("INVALID TIME: Must be HH:MM");
}


Also, with this problem I'm still having the eternal problem of getting
infinite alert boxes if I click on the textbox for the inTime and the
textbox for the timeOut (or vice versa) right after each other. Any
thoughts for this, other than setting the variable to not mess with it
if the other element is validating?

Ken
Jul 20 '05 #4
Lee
Kenneth said:
All I'm trying to do now is set the focus on the proper time element.
I'm trying to do this by feeding the element name into the function
(i.e. validateTimeFor mat('timeIn',th is.value);)

Don't pass the name. Just pass a reference to the element:

onchange="valid ateTimeFormat(t his)"
function validateTimeFor mat(ref){
// validate ref.value
// ...
ref.focus();
// ...
}

Jul 20 '05 #5
Lee
Kenneth said:
Also, with this problem I'm still having the eternal problem of getting
infinite alert boxes if I click on the textbox for the inTime and the
textbox for the timeOut (or vice versa) right after each other. Any
thoughts for this, other than setting the variable to not mess with it
if the other element is validating?


Don't use the onBlur envent handler for validation.
Is this an assignment for a class?

Jul 20 '05 #6
JRS: In article <10************ *@corp.supernew s.com>, seen in
news:comp.lang. javascript, Kenneth <ke*****@NOSPAM .pardue.com> posted at
Thu, 12 Feb 2004 15:59:28 :-
I'm having some serious problems debugging a script that I'm trying to make
work. I'm working on a form where a user can type in a time (in the format
of HH:MM), and another script automatically calculate how much time is
inbetween.

That part of it is working fine, but what ISN'T working fine is the script
that validates whether or not the user has entered the time in proper
syntax, and to make sure that the Time In does not come after the Time Out.
Read the newsgroup FAQ; see below.

Here's the two functions, one to validate In and one to validate Out:
function validateInTimeF ormat(){
// This function validates whether or not a user has entered proper time
into the form
var inTime = document.frm.in Time.value;

if (validatingOutT ime == false) {
Silly. Use if (!validatingOut Time) { for that
if (inTime.indexOf (":") == "-1"){
alert("Time In: You didn't put a \":\"");
this.document.f rm.inTime.focus ();
validatingInTim e = true;
return false;
} else if ((inTime.substr (0,inTime.index Of(":"))<1) ||
(inTime.substr (0,inTime.index Of(":"))>12)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.in Time.focus();
validatingInTim e = true;
return false;
} else if ((inTime.substr (inTime.indexOf (":")+1,inTime. length) < 0) ||
(inTime.substr (inTime.indexOf (":")+1,inTime. length) > 59)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.in Time.focus();
validatingInTim e = true;
return false;
} else {
validatingInTim e = false;
return true;
}

}
}
Tedious. Use a RegExp such as /^\[0-2]\d:[0-5]\d$/ - though that
only does part of what it could.
function validateOutTime Format(){
// This function validates whether or not a user has entered proper time
into the form
var outTime = document.frm.ou tTime.value;

if (validatingInTi me == false) {
if (outTime.indexO f(":") == "-1"){
alert("Time In: You didn't put a \":\"");
this.document.f rm.outTime.focu s();
validatingOutTi me = true;
return false;
} else if ((outTime.subst r(0,outTime.ind exOf(":"))<1) ||
(outTime.subst r(0,outTime.ind exOf(":"))>12)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.ou tTime.focus();
validatingOutTi me = true;
return false;
} else if ((outTime.subst r(outTime.index Of(":")+1,outTi me.length) < 0) ||
(outTime.subst r(outTime.index Of(":")+1,outTi me.length) > 59)) {
alert("Please check to make sure your time is in the proper format
(hh/mm)");
document.frm.ou tTime.focus();
validatingOutTi me = true;
return false;
} else {
validatingOutTi me = false;
return true;
}

}
}
Duplicating code like that is really stupid. Use a validation function
controlled by parameters.
Here's how i have it called in the page:

<br />Time: In &nbsp;<input name="inTime" type="text"
class="formInp utText" id="inTime" size="5" onblur="return
validateInTime Format();" />
<select name="inTime12H r" class="formInpu tText" id="inTime12Hr" >
<option value="AM">AM</option>
<option value="PM">PM</option>
</select><br />
Time: Out <input name="outTime" type="text" class="formInpu tText"
id="outTime" size="5" onblur="return validateOutTime Format();" />
<select name="outTime12 Hr" class="formInpu tText" id="outTime12Hr ">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
FYI: I know I haven't done anything in the functions with the AM and PM.
Eventually I'll just have it add 12 hours to the result if it's PM, but I
haven't reached that point yet.
Don't use AM & PM. Nearly every country in the world understands how
much better the 24-h clock is, except for devices with a minute hand and
an hour hand. Granted, the 12-h clock is better as a programming
exercise, for which superfluous complications are beneficial.
I've been working in IE and also in Mozilla
Firefox (with the JavaScript Debugger). I get everything from "Error:
outTime has no properties" to some crazy nsexception type stuff in Mozilla.
I think the latter occurs when trying to focus the cursor back on the field
in question. It (somewhat) works in IE but not in Mozilla at all. Also,
noting the "if validatingInTim e==false" stuff, I had to do that because it
would automatically jump between the inTime field and outTiem field into
eternity if you clicked on one and then the other. Any clues on how much
I've screwed this up? JavaScript is SOOOOOOOOOOO difficult to debug.


Greatly. See below.

You need to learn to modularise. Separate the validation of the time
string from the handling of the display, but combine it with returning
the time numerically, if it is to be so used.

inTime = ReadUSTime(inSt ring)
OK = inTime >= 0
if (!OK) alert(...)
Note that given two civil times such as 00:30 and 23:30 you cannot
actually calculate the amount of time in between; it may be 22, 23, or
24 hours (or, AIUI, just possibly 22.5 or 23.5 hours).

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2610
by: EviL KerneL | last post by:
Hi - I am trying to figure out a way to enforce the validation included for this form based on whether the user chooses "email" or "phone" as the contact choice. Right now it is set to enforce validation on both. Is there a way to link the drop-down choice to the correspondent validation section while disabling validation for the other one? here's what I presently have:
11
1262
by: J. J. Cale | last post by:
FOA I want to apologize because the page below is in Hebrew and you'll see giberish. But for the brave here is the link. www.carmenchange.com Either the left or right select box must be set to default (local currency) otherwise it evaluates the sale with the foreign currencies. Enter the amount under the foreign currency. Every once in a while if fudges. 2.50 X 10 =24.9........06 for those who can deal with the code these functions...
16
2252
by: Hosh | last post by:
I have a form on a webpage and want to use JavaScript validation for the form fields. I have searched the web for form validation scripts and have come up with scripts that only validate individual fields, such as an "Email Validation Script" or a "Phone Validation Script". Is it ok to put all these scripts on page as they are or should they be joined in some way together to be one script? I'm a total JavaScript newbie and am completely...
0
1820
by: Oliver Elphick | last post by:
The attached proposal is written primarily for Debian. Its motivation is that the current package upgrade process is pretty flaky and also that the current packaging does not really provide for multiple simultaneous postmasters, which are wanted by people hosting several database clusters. I assume these proposals may also be of interest to Red Hat packagers. I am copying it to the PostgreSQL list in case there are any obvious...
188
7252
by: christopher diggins | last post by:
I have posted a C# critique at http://www.heron-language.com/c-sharp-critique.html. To summarize I bring up the following issues : - unsafe code - attributes - garbage collection - non-deterministic destructors - Objects can't exist on the stack - Type / Reference Types
2
2686
by: Dnna | last post by:
I have a table which is bound to an Internet Explorer XML data island. I'm using ASP.NET's client-side validators for an input field in the table. The problem is that if the input fields are in a table that is bound to the island (such that the rows are dynamically generated by IE from the XML data island), the validators do not work. If the table is not bound, the validators do work, but then I don't have the table iterating through...
12
1349
by: NuB | last post by:
The validation controls are giving me a headache. here is what i'm trying to do and so far what I've tried has not worked. I need to hide my grid if the page is not valid how can i accomplish that? I have one validation control that gives an error if there is no data returned, so if the page is not valid on another search i need that to go away. How can i hide and show controls and labels bases on the page.isvalid
20
4284
by: mike | last post by:
I help manage a large web site, one that has over 600 html pages... It's a reference site for ham radio folks and as an example, one page indexes over 1.8 gb of on-line PDF documents. The site is structured as an upside-down tree, and (if I remember correctly) never more than 4 levels. The site basically grew (like the creeping black blob) ... all the pages were created in Notepad over the last
6
2401
by: Steve Ryan | last post by:
can anyone send me to some good examples of edit in place for data frid columns i see dot net let me assign a control in the IDE any good sources of reading on editing columns with controls and setting styles thanks
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9996
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.