Date Validation for 3 Dropdowns!?

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

    Date Validation for 3 Dropdowns!?

    Hi everyone,

    This problem has been puzzling me for a fair time now, and has severely
    frustrated me!! Perhaps I'm just not getting the syntax right, but the
    problem is rather simple...

    Take a look at:


    The small booking form on the left, we're using the same one, but we need to
    add javascript validation to ensure the following...

    - That a date cannot be selected thats in the past
    - That an invalid date cannot be selected, i.e. Feb 30th

    I would also like it if when you make a selection in the first box, it
    mirrors it to the second, but perhaps a day later? I think this may be a
    little tricky?

    REALLY appreciate anyones help, I've tried so many scripts, and just cannot
    get one working.

    Cheers, Ash


  • Ash

    #2
    Re: Date Validation for 3 Dropdowns!?

    Actually, here's the lump of javascript that the form uses, you can see some
    Javascript that I tried to make sure one date wasn't before the other...but
    it didn't work!?

    ------------

    <SCRIPT language="JavaS cript" TYPE="text/javascript">
    function doCheckAvail(){
    if(validateFiel ds()){
    var form = document.myForm ;

    //collect your screen data
    var arrDay = form.ARRIVAL_DA Y.value;
    var arrMon = form.ARRIVAL_MO NTH.value;
    var arrYear = form.ARRIVAL_YE AR.value;
    var depDay = form.DEPARTURE_ DAY.value;
    var depMon = form.DEPARTURE_ MONTH.value;
    var depYear = form.DEPARTURE_ YEAR.value;
    var adult = form.ADULTS.val ue;
    var child = form.CHILDREN.v alue;

    var chainCode = "vones";
    var hotelCode = "<%= TheHotelCode %>";
    var email = "<%= TheHotelEmail %>";
    var website = "http%3a%2f%2fw ww.<%= TheHotelWebsite %>";
    var barServer =
    "https://agent.synxis.co m/bar/BarServlet?sele ctor=Login";


    //start creating the url
    var url = barServer+
    "&cid="+chainCo de+ //your chain code
    "&hid="+hotelCo de+ //your hotel code
    "&hea="+ema il+ //your hotel contact email
    "&url="+website + //your hotel website
    "&locale=en_GB" + //the locale you are in
    "&checkAvailabi lity=true"+ //alerts that you are
    going to the room page
    "&bam="+arr Mon+ //arrival month
    "&bad="+arr Day+ //arrival day
    "&bay="+arrYear + //arrival year
    "&bdm="+dep Mon+ //departure month
    "&bdd="+dep Day+ //departure day
    "&bdy="+depYear + //departure year
    "&noa="+adu lt+ //# of adults
    "&noc="+chi ld; //# of children

    //now pop-up the new window with this url.
    document.locati on = url;
    // window.open(url , "BAR",
    "width=778,heig ht=600,status=y es,resizable=ye s,scrollbars=ye s");
    }
    else{
    alert("You must enter valid information");
    }
    }

    function validateFields( ) {

    // ASH: Concatenate the two dates into single variables - OR AT LEAST
    TRY!!!
    // var form = document.myForm ;

    // var arrDay = parseInt(form.A RRIVAL_DAY.valu e);
    // var arrMon = parseInt(form.A RRIVAL_MONTH.va lue);
    // var arrYear = parseInt(form.A RRIVAL_YEAR.val ue);
    // var depDay = parseInt(form.D EPARTURE_DAY.va lue);
    // var depMon = parseInt(form.D EPARTURE_MONTH. value);
    // var depYear = parseInt(form.D EPARTURE_YEAR.v alue);


    // var TheFromDate = arrDay+"/"+arrMon+"/"+arrYear
    // var TheToDate = depDay+"/"+depMon+"/"+depYear

    // if (TheFromDate) > (TheToDate) {
    // alert('The Date of Arrival must be prior to the Date of Departures')
    // alert(TheFromDa te+" & "+TheToDate )
    // }

    return true;
    }

    </SCRIPT>


    Comment

    • Michael Winter

      #3
      Re: Date Validation for 3 Dropdowns!?

      Ash wrote:
      [color=blue]
      > Actually, here's the lump of javascript that the form uses, [...][/color]

      Rather than using that code to create the submission, why don't you just
      submit the form properly?

      function isValidDate(dt, y, m, d) {
      return (y == dt.getFullYear( )) && (m == dt.getMonth())
      && (d = dt.getDate());
      }

      function isValidSubmissi on(form) {
      var elem = form.elements,
      now = new Date(),
      y, m, d, arr, dep;

      arr = new Date(
      y = +elem.bay.value ,
      m = elem.bam.value - 1,
      d = +elem.bad.value
      );
      if(!isValidDate (arr, y, m, d)) {
      /* Arrival date is not valid. */
      return false;
      }
      if(arr <= now) {
      /* Arrival date is before today. */
      return false;
      }

      dep = new Date(
      y = +elem.bdy.value ,
      m = elem.bdm.value - 1,
      d = +elem.bdd.value
      );
      if(!isValidDate (dep, y, m, d)) {
      /* Departure date is not valid. */
      return false;
      }
      if(dep < arr) {
      /* Departure date is before arrival date. */
      return false;
      }
      return true;
      }

      <form method="get"
      action="https://agent.synxis.co m/bar/BarServlet?sele ctor=Login"
      onsubmit="retur n isValidSubmissi on(this);">
      <input name="cid" type="hidden" value="vones">
      <input name="hid" type="hidden" value="<%= TheHotelCode %>">
      <input name="hea" type="hidden" value="<%= TheHotelEmail %>">
      <input name="url" type="hidden"
      value="http://www.<%= TheHotelWebsite %>">
      <input name="locale" type="hidden" value="en_GB">
      <input name="checkAvai lability" type="hidden" value="true">
      <input name="noc" type="hidden" value="0">

      <!-- Arrival month -->
      <select name="bam" size="1">
      <!-- ... -->
      </select>
      <!-- Arrival day -->
      <select name="bad" size="1">
      <!-- ... -->
      </select>
      <!-- Arrival year -->
      <select name="bay" size="1">
      <!-- ... -->
      </select>

      <!-- Departure month -->
      <select name="bdm" size="1">
      <!-- ... -->
      </select>
      <!-- Departure day -->
      <select name="bdd" size="1">
      <!-- ... -->
      </select>
      <!-- Departure year -->
      <select name="bdy" size="1">
      <!-- ... -->
      </select>

      <!-- Number of adults -->
      <select name="noa" size="1">
      <!-- ... -->
      </select>
      </form>

      The number of children (noc) is included amongst the hidden elements as
      you haven't provided any way to input that information.

      At the present moment, an arrival date that matches the current day will
      be considered invalid. Changing it to be valid is not trivial. Are there
      enough hours left in the day to process the booking? If the visitor is
      thousands of miles away (and you don't know if they are or not), did
      they really intend to book today?
      [color=blue]
      > //now pop-up the new window with this url.[/color]

      If you really do want to use a pop-up, then you could include this function:

      function submitToPopup(f orm) {
      if('function' == typeof this.open) {
      this.open(
      '',
      form.target,
      'width=778,heig ht=600,status,r esizable,scroll bars
      );
      }
      return true;
      }

      alter the submit listener to:

      onsubmit="retur n isValidSubmissi on(this) && submitToPopup(t his);"

      and add a target attribute to the FORM element:

      <form target="booking " ...>

      [snip]

      Hope that helps,
      Mike

      --
      Michael Winter
      Replace ".invalid" with ".uk" to reply by e-mail.

      Comment

      • Mick White

        #4
        Re: Date Validation for 3 Dropdowns!?

        Ash wrote:
        [color=blue]
        > Actually, here's the lump of javascript that the form uses, you can see some
        > Javascript that I tried to make sure one date wasn't before the other...but
        > it didn't work!?
        >
        > ------------[/color]




        Mick
        [color=blue]
        >
        > <SCRIPT language="JavaS cript" TYPE="text/javascript">
        > function doCheckAvail(){
        > if(validateFiel ds()){
        > var form = document.myForm ;
        >
        > //collect your screen data
        > var arrDay = form.ARRIVAL_DA Y.value;
        > var arrMon = form.ARRIVAL_MO NTH.value;
        > var arrYear = form.ARRIVAL_YE AR.value;
        > var depDay = form.DEPARTURE_ DAY.value;
        > var depMon = form.DEPARTURE_ MONTH.value;
        > var depYear = form.DEPARTURE_ YEAR.value;
        > var adult = form.ADULTS.val ue;
        > var child = form.CHILDREN.v alue;
        >
        > var chainCode = "vones";
        > var hotelCode = "<%= TheHotelCode %>";
        > var email = "<%= TheHotelEmail %>";
        > var website = "http%3a%2f%2fw ww.<%= TheHotelWebsite %>";
        > var barServer =
        > "https://agent.synxis.co m/bar/BarServlet?sele ctor=Login";
        >
        >
        > //start creating the url
        > var url = barServer+
        > "&cid="+chainCo de+ //your chain code
        > "&hid="+hotelCo de+ //your hotel code
        > "&hea="+ema il+ //your hotel contact email
        > "&url="+website + //your hotel website
        > "&locale=en_GB" + //the locale you are in
        > "&checkAvailabi lity=true"+ //alerts that you are
        > going to the room page
        > "&bam="+arr Mon+ //arrival month
        > "&bad="+arr Day+ //arrival day
        > "&bay="+arrYear + //arrival year
        > "&bdm="+dep Mon+ //departure month
        > "&bdd="+dep Day+ //departure day
        > "&bdy="+depYear + //departure year
        > "&noa="+adu lt+ //# of adults
        > "&noc="+chi ld; //# of children
        >
        > //now pop-up the new window with this url.
        > document.locati on = url;
        > // window.open(url , "BAR",
        > "width=778,heig ht=600,status=y es,resizable=ye s,scrollbars=ye s");
        > }
        > else{
        > alert("You must enter valid information");
        > }
        > }
        >
        > function validateFields( ) {
        >
        > // ASH: Concatenate the two dates into single variables - OR AT LEAST
        > TRY!!!
        > // var form = document.myForm ;
        >
        > // var arrDay = parseInt(form.A RRIVAL_DAY.valu e);
        > // var arrMon = parseInt(form.A RRIVAL_MONTH.va lue);
        > // var arrYear = parseInt(form.A RRIVAL_YEAR.val ue);
        > // var depDay = parseInt(form.D EPARTURE_DAY.va lue);
        > // var depMon = parseInt(form.D EPARTURE_MONTH. value);
        > // var depYear = parseInt(form.D EPARTURE_YEAR.v alue);
        >
        >
        > // var TheFromDate = arrDay+"/"+arrMon+"/"+arrYear
        > // var TheToDate = depDay+"/"+depMon+"/"+depYear
        >
        > // if (TheFromDate) > (TheToDate) {
        > // alert('The Date of Arrival must be prior to the Date of Departures')
        > // alert(TheFromDa te+" & "+TheToDate )
        > // }
        >
        > return true;
        > }
        >
        > </SCRIPT>
        >
        >[/color]

        Comment

        • Ash

          #5
          Re: Date Validation for 3 Dropdowns!?

          > Rather than using that code to create the submission, why don't you just[color=blue]
          > submit the form properly?
          >
          > function isValidDate(dt, y, m, d) {
          > return (y == dt.getFullYear( )) && (m == dt.getMonth())
          > && (d = dt.getDate());[/color]

          Wow thanks for your detailed response, thats excellent, I really struggle
          with Javascript - not to understand its logic, but to correctly set out its
          syntax, stumps me every time!

          I see your reasoning behind suggesting to submit the form 'properly',
          trouble is the people behind the hotel booking application prefer us to
          follow their basic code model, with the addition of our own validation. I'm
          quite happy with this as it enables them to support any issues we have.

          Taking your above function above (ValidDate), how could we simply expand on
          that, so as when the user clicks CHECK/BOOK, the current script will check
          that both are valid, and if either are invalid, it'll simply popup an alert
          to say so?

          Cheers, Ash


          Comment

          • Ash

            #6
            Re: Date Validation for 3 Dropdowns!?

            Very smart, will take a look at the logic behind that now.

            Thanks!


            "Mick White" <mwhite13BOGUS@ rochester.rr.co m> wrote in message
            news:ye5be.7879 $Bc7.5179@twist er.nyroc.rr.com ...[color=blue]
            > Ash wrote:
            >[color=green]
            >> Actually, here's the lump of javascript that the form uses, you can see
            >> some Javascript that I tried to make sure one date wasn't before the
            >> other...but it didn't work!?
            >>
            >> ------------[/color]
            >
            > http://www.mickweb.com/b_and_b/index1.html[/color]


            Comment

            • Dr John Stockton

              #7
              Re: Date Validation for 3 Dropdowns!?

              JRS: In article <mo4be.19156$G8 .5402@text.news .blueyonder.co. uk>, dated
              Mon, 25 Apr 2005 11:20:50, seen in news:comp.lang. javascript, Michael
              Winter <m.winter@bluey onder.co.invali d> posted :[color=blue]
              >Ash wrote:
              >[color=green]
              >> Actually, here's the lump of javascript that the form uses, [...][/color]
              >
              >Rather than using that code to create the submission, why don't you just
              >submit the form properly?
              >
              > function isValidDate(dt, y, m, d) {
              > return (y == dt.getFullYear( )) && (m == dt.getMonth())
              > && (d = dt.getDate());
              > }[/color]

              One does not need all three tests (possible exception is if the function
              must give the right answer for 0000-02-29 (that could be fixed with
              something like Arr = new Date(y+4000, m-48000, d) ), but that will
              not apply, it seems, in this case).



              For drop-downs in which it is not possible to select an invalid
              Gregorian date, see in <URL:http://www.merlyn.demo n.co.uk/js-date6.htm>.
              That code requires javascript to (re)build the day control, IIRC; but
              the code could be modified to put 31 days in every month by HTML and
              correct that only if javascript is available.



              If there is to be a selector for arrival and then one for departure, the
              latter can likewise be made to offer only dates for which departure can,
              or must, follow arrival.


              ISTM better, rather than having to validate the customer's choice, to
              arrange matters so that he can make only valid choices. Of course, if
              there is a server, there should at some stage be server-side validation.


              If this is a short-stay business, how about Y M D drop-downs for
              arrival, then a selector for length of stay, then a display of the
              resultant departure date? For each selected date, the day-of-week
              should probably be shown; indeed, a D entries in a Y M D drop-down can
              show not only D but also its DoW.

              An OP posting via BT should surely not be using FFF order, but Y M D.

              --
              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
              <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of 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

              • Ash

                #8
                Re: Date Validation for 3 Dropdowns!?


                "Dr John Stockton" <spam@merlyn.de mon.co.uk> wrote in message
                news:wtPgnJA4CU bCFwuD@merlyn.d emon.co.uk...[color=blue]
                > JRS: In article <mo4be.19156$G8 .5402@text.news .blueyonder.co. uk>, dated
                > Mon, 25 Apr 2005 11:20:50, seen in news:comp.lang. javascript, Michael
                > Winter <m.winter@bluey onder.co.invali d> posted :[color=green]
                >>Ash wrote:[/color][/color]


                Thanks for your incredibly detailed reply, my understanding of other
                logical languages is fairly good, but its the actual implementation of any
                javascript that my ability to get the correct syntax seems to fail - I will
                give it a go, but I'm sure I'll fail in actually amending my existing page
                to incorporate this code.

                In the current script, you'll notice a function...

                function validateFields( ){
                return true;
                }

                To keep things simple, I would like to insert a code block into this
                function that will simply...

                //1. Arrival date is at least today (you may have more
                restrictions)
                //2. Departure date is after arrival
                //3. Arrival and Departure dates are valid dates.

                I feel real guilty asking for this, but would it be possible to construct
                the actual code that I could dump straight into this function?

                Really appreciate your help, at least from there I can see how the syntax
                works in the context, and perhaps learn something for the future, hehe!

                Cheers, Ash


                Comment

                • @sh

                  #9
                  Re: Date Validation for 3 Dropdowns!?

                  Before I try something more complex, I'm staying simple and have tried
                  this...

                  function validateFields( ) {

                  if (document.myFor m.ARRIVAL_DAY.v alue = '02') &&
                  (document.myFor m.ARRIVAL_MONTH .value > '28') {
                  alert('Invalid date');
                  return false;
                  }
                  else
                  {
                  return true;
                  }

                  ....But it doesn't work, what am I doing wrong? I get a 'Syntax Error'.

                  Cheers, Ash


                  Comment

                  • @sh

                    #10
                    Re: Date Validation for 3 Dropdowns!?

                    Ooooops, ignore my last post....I see a few errors there but thats another
                    story...

                    I'm starting from the top now and outputing the variables I'm trying to deal
                    with to an alert() prompt, however I'm just getting '[object]' popping up,
                    does this mean it cannot interpret the value??

                    Cheers, Ash


                    Comment

                    • Mick White

                      #11
                      Re: Date Validation for 3 Dropdowns!?

                      @sh wrote:
                      [color=blue]
                      > Before I try something more complex, I'm staying simple and have tried
                      > this...
                      >
                      > function validateFields( ) {
                      >
                      > if (document.myFor m.ARRIVAL_DAY.v alue = '02') &&
                      > (document.myFor m.ARRIVAL_MONTH .value > '28') {
                      > alert('Invalid date');
                      > return false;
                      > }
                      > else
                      > {
                      > return true;
                      > }
                      >
                      > ...But it doesn't work, what am I doing wrong? I get a 'Syntax Error'.[/color]

                      function validateFields( ) {
                      var d=document.myFo rm
                      if (parseInt(d.ARR IVAL_DAY.value, 10) == 2 &&
                      d.ARRIVAL_MONTH .value > 28) {
                      alert('Invalid date');
                      return false;
                      }
                      return true;
                      }
                      Mick

                      Comment

                      • Michael Winter

                        #12
                        Re: Date Validation for 3 Dropdowns!?

                        Ash wrote:
                        [color=blue]
                        > Taking your [...] function [...] (ValidDate), how could we simply expand on
                        > that, so as when the user clicks CHECK/BOOK, the current script will check
                        > that both are valid, and if either are invalid, it'll simply popup an alert
                        > to say so?[/color]

                        You can use the original function. All you really need to do is alter
                        the control names I used. So, for example

                        elem.bay.value

                        would be changed to

                        elem.ARRIVAL_YE AR.value

                        There are six control references in all, used in the two Date
                        constructors. The sequence 'ba' should be replaced by 'ARRIVAL_' and
                        'bd' by 'DEPARTURE_'. The remaining characters - 'y', 'm', and 'd' - are
                        obviously 'YEAR', 'MONTH' and 'DAY'.

                        If you want to show warnings, the comments show where failures are found
                        in the code and what caused them. You can use the alert function to
                        display a string.

                        There really isn't that much to edit.

                        Mike

                        --
                        Michael Winter
                        Replace ".invalid" with ".uk" to reply by e-mail.

                        Comment

                        • Michael Winter

                          #13
                          Re: Date Validation for 3 Dropdowns!?

                          Dr John Stockton wrote:
                          [color=blue]
                          > JRS: In article <mo4be.19156$G8 .5402@text.news .blueyonder.co. uk>, dated
                          > Mon, 25 Apr 2005 11:20:50, seen in news:comp.lang. javascript, Michael
                          > Winter <m.winter@bluey onder.co.invali d> posted :[/color]

                          [snip]
                          [color=blue][color=green]
                          >> function isValidDate(dt, y, m, d) {
                          >> return (y == dt.getFullYear( )) && (m == dt.getMonth())
                          >> && (d = dt.getDate());
                          >> }[/color]
                          >
                          > One does not need all three tests [...][/color]

                          Perhaps not. I don't see any particular reason not to include them all,
                          however it would probably be better to change the order of evaluation as
                          the year is only likely to change in December (when input restrictions
                          are imposed). It would potentially shorten the time necessary to
                          discover invalid dates, but still add little overhead to valid ones.
                          [color=blue]
                          > [...] <URL:http://www.merlyn.demo n.co.uk/js-date6.htm>.
                          > [...] the code could be modified to put 31 days in every month by
                          > HTML and correct that only if javascript is available.[/color]

                          And probably should be. I'll probably post something later.
                          [color=blue]
                          > If there is to be a selector for arrival and then one for departure, the
                          > latter can likewise be made to offer only dates for which departure can,
                          > or must, follow arrival.[/color]

                          True. However it would still be prudent to assume that such a selector
                          cannot be created, and 'basic' validation should still be carried out on
                          the client (and the server, of course).
                          [color=blue]
                          > [...] Of course, if there is a server, there should at some stage be
                          > server-side validation.[/color]

                          I get the impression that the third-party service relies on client-side
                          validation created by its users. I'm not about to test that theory
                          through an account that belongs to someone else, though.

                          [snip]
                          [color=blue]
                          > An OP posting via BT should surely not be using FFF order [...][/color]

                          FFF?

                          Mike

                          --
                          Michael Winter
                          Replace ".invalid" with ".uk" to reply by e-mail.

                          Comment

                          • Lasse Reichstein Nielsen

                            #14
                            Re: Date Validation for 3 Dropdowns!?

                            Michael Winter <m.winter@bluey onder.co.invali d> writes:
                            [color=blue]
                            > Dr John Stockton wrote:[/color]
                            [color=blue][color=green]
                            >> One does not need all three tests [...][/color]
                            >
                            > Perhaps not. I don't see any particular reason not to include them
                            > all, however it would probably be better to change the order of
                            > evaluation as the year is only likely to change in December (when
                            > input restrictions are imposed). It would potentially shorten the time
                            > necessary to discover invalid dates, but still add little overhead to
                            > valid ones.[/color]

                            A good choice. It is a rare error that changes the year and not the
                            month. Indeed, most non-deliberate errors will be only a few days off
                            (e.g., 31st of April) and will error on both date and month.

                            Moving the year check last will guarantee that it is only performed
                            for valid dates (but that goes for any of the checks if placed third).

                            (btw, remember to change the "=" to "==" in the date comparison).
                            [color=blue][color=green]
                            >> An OP posting via BT should surely not be using FFF order [...][/color]
                            >
                            > FFF?[/color]

                            "Fred Flintstone Format", Dr. Stockton's own name for MM/DD/YY format.
                            <URL:http://www.merlyn.demo n.co.uk/datefmts.htm>

                            /L
                            --
                            Lasse Reichstein Nielsen - lrn@hotpop.com
                            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                            'Faith without judgement merely degrades the spirit divine.'

                            Comment

                            • Michael Winter

                              #15
                              Re: Date Validation for 3 Dropdowns!?

                              Lasse Reichstein Nielsen wrote:

                              [snip]
                              [color=blue]
                              > (btw, remember to change the "=" to "==" in the date comparison).[/color]

                              Oops. Thank you. That was careless of me.

                              In case the OP doesn't quite know what Lasse is referring to, the
                              isValidDate function should read:

                              function isValidDate(dt, y, m, d) {
                              return (dt.getDate() == d) && (dt.getMonth() == m)
                              && (dt.getFullYear () == y);
                              }

                              I also thought I'd take my own advice and reverse the order of the
                              operands so that the method call, which cannot be assigned to without
                              causing a run-time error, is on the left-hand side.

                              Mike

                              --
                              Michael Winter
                              Replace ".invalid" with ".uk" to reply by e-mail.

                              Comment

                              Working...