MAJOR headache with Time Validation Script

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kenneth

    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


  • Brian Genisio

    #2
    Re: MAJOR headache with Time Validation Script

    Kenneth wrote:[color=blue]
    > 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.[/color]

    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");
    }

    Comment

    • Kenneth

      #3
      Re: MAJOR headache with Time Validation Script

      Brian Genisio wrote:[color=blue]
      > Kenneth wrote:
      >[color=green]
      >> 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.[/color]
      >
      >
      > 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");
      > }
      >[/color]

      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

      Comment

      • Kenneth

        #4
        Re: MAJOR headache with Time Validation Script

        Brian Genisio wrote:
        [color=blue]
        > Kenneth wrote:
        >[color=green]
        >> 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.[/color]
        >
        >
        > 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");
        > }
        >[/color]

        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

        Comment

        • Lee

          #5
          Re: MAJOR headache with Time Validation Script

          Kenneth said:
          [color=blue]
          >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);)[/color]


          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();
          // ...
          }

          Comment

          • Lee

            #6
            Re: MAJOR headache with Time Validation Script

            Kenneth said:
            [color=blue]
            >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?[/color]

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

            Comment

            • Dr John Stockton

              #7
              Re: MAJOR headache with Time Validation Script

              JRS: In article <102ntrgqnpte43 b@corp.supernew s.com>, seen in
              news:comp.lang. javascript, Kenneth <kenneth@NOSPAM .pardue.com> posted at
              Thu, 12 Feb 2004 15:59:28 :-
              [color=blue]
              >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.[/color]

              Read the newsgroup FAQ; see below.

              [color=blue]
              >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) {[/color]

              Silly. Use if (!validatingOut Time) { for that
              [color=blue]
              > 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;
              > }
              >
              > }
              >}[/color]

              Tedious. Use a RegExp such as /^\[0-2]\d:[0-5]\d$/ - though that
              only does part of what it could.
              [color=blue]
              >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;
              > }
              >
              > }
              >}[/color]

              Duplicating code like that is really stupid. Use a validation function
              controlled by parameters.
              [color=blue]
              >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.[/color]

              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.
              [color=blue]
              > 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.[/color]

              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.

              Comment

              Working...