Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Date javascript

Posted on 2001-06-02
25
Medium Priority
?
292 Views
Last Modified: 2013-12-24
I have a date text box, I want to have it so a user can't enter a old date prior from todays date. They must enter a date  either today or a future date

Then on the flip side...

I also have another text box that a I want to prevent the user from entering a future date from today's date.

Thanks for the HELP,

Kim
0
Comment
Question by:kim24
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 9
  • 3
  • +1
25 Comments
 
LVL 5

Expert Comment

by:Yog
ID: 6148703
here is it

for example enter 041500 or 061500 etc

<html>
<head>
<script language="JavaScript">
function DatePosition(dateString,dateType) {
/*
   function DatePosition
   parameters: dateString dateType
   returns: integer (-1, 0, 1)
   
   dateString is a date passed as a string in the following
   formats:

   type 1 : 19970529
   type 2 : 970529
   type 3 : 29/05/1997
   type 4 : 29/05/97
   type 5 : 05/29/1997
   type 6 : 05291997
   type 7 : 052997
   
   dateType is a numeric integer from 1 to 7, representing
   the type of dateString passed, as defined above.

   Returns -1 if the date passed is behind todays date
   Returns 0 if the date passed is equal to todays date
   or if dateType is not 1 to 7
   Returns 1 if the date passed is ahead of todays date
   
   Added Y2K checking.  (Works for any century cross over)
*/


    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());
    var century = parseInt(now.getYear()/100)*100;
       
    if (dateType == 1)
        var date = new Date(dateString.substring(0,4),
                            dateString.substring(4,6)-1,
                            dateString.substring(6,8));
    else if (dateType == 2)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(0,2)))
        {
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        else
        {
            var date = new Date(century-100+parseInt(dateString.substring(0,2)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
       
    }
    else if (dateType == 3)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else if (dateType == 4)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(6,8)))
        {
            alert(century+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        else
        {
            alert(century-100+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
       
    }
    else if (dateType == 5)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(0,2)-1,
                            dateString.substring(3,5));
    else if (dateType == 6)
        var date = new Date(dateString.substring(4,8),
                            dateString.substring(0,2)-1,
                            dateString.substring(2,4));
    else if (dateType == 7)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(4,6)))
        {
            alert('datestring Century:',century+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        else
        {
            alert('datestring Century:',century-100+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
       
    }
    else
        return false;

    if (date < today)
    {
        alert("Behind today");
        return -1;
    }
    else if (date > today)
    {
        alert("After today");
        return 1;
       
    }
    else
    {
        alert("Same as today");
        return 0;
    }
}

</script>

<script language="JavaScript">
function doit() {
alert(DatePosition(document.myform.mytext.value,7));
}
</script>
</head>
<body>
<form name="myform">
<input type="text" name="mytext" >
<input type="button" name="test" value="test" onclick="doit()">
</form>
</body>
</html>

cheers.
0
 
LVL 5

Expert Comment

by:Yog
ID: 6148709
just commeted the alert's here lol
<html>
<head>
<script language="JavaScript">
function DatePosition(dateString,dateType) {
/*
   function DatePosition
   parameters: dateString dateType
   returns: integer (-1, 0, 1)
   
   dateString is a date passed as a string in the following
   formats:

   type 1 : 19970529
   type 2 : 970529
   type 3 : 29/05/1997
   type 4 : 29/05/97
   type 5 : 05/29/1997
   type 6 : 05291997
   type 7 : 052997
   
   dateType is a numeric integer from 1 to 7, representing
   the type of dateString passed, as defined above.

   Returns -1 if the date passed is behind todays date
   Returns 0 if the date passed is equal to todays date
   or if dateType is not 1 to 7
   Returns 1 if the date passed is ahead of todays date
   
   Added Y2K checking.  (Works for any century cross over)
*/


    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());
    var century = parseInt(now.getYear()/100)*100;
       
    if (dateType == 1)
        var date = new Date(dateString.substring(0,4),
                            dateString.substring(4,6)-1,
                            dateString.substring(6,8));
    else if (dateType == 2)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(0,2)))
        {
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
        else
        {
            var date = new Date(century-100+parseInt(dateString.substring(0,2)),
                            parseInt(dateString.substring(2,4)-1),
                            dateString.substring(4,6));
        }
       
    }
    else if (dateType == 3)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(3,5)-1,
                            dateString.substring(0,2));
    else if (dateType == 4)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(6,8)))
        {
            //alert(century+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
        else
        {
           //alert(century-100+parseInt(dateString.substring(6,8)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(3,5)-1),
                            dateString.substring(0,2));
        }
       
    }
    else if (dateType == 5)
        var date = new Date(dateString.substring(6,10),
                            dateString.substring(0,2)-1,
                            dateString.substring(3,5));
    else if (dateType == 6)
        var date = new Date(dateString.substring(4,8),
                            dateString.substring(0,2)-1,
                            dateString.substring(2,4));
    else if (dateType == 7)
    {
        if ((now.getYear()%100)>=parseInt(dateString.substring(4,6)))
        {
            //alert('datestring Century:',century+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
        else
        {
            //alert('datestring Century:',century-100+parseInt(dateString.substring(4,6)),'<P>');
            var date = new Date(century-100+parseInt(dateString.substring(4,6)),
                            parseInt(dateString.substring(0,2)-1),
                            dateString.substring(2,4));
        }
       
    }
    else
        return false;

    if (date < today)
    {
        alert("Behind today");
       // return -1;
    }
    else if (date > today)
    {
        alert("After today");
        //return 1;
       
    }
    else
    {
        alert("Same as today");
       // return 0;
    }
}

</script>

<script language="JavaScript">
function doit() {
DatePosition(document.myform.mytext.value,7);
}
</script>
</head>
<body>
<form name="myform">
<input type="text" name="mytext" >
<input type="button" name="test" value="test" onclick="doit()">
</form>
</body>
</html>
0
 

Author Comment

by:kim24
ID: 6148770
Yog, thanks but I should have been more clear in my question.

I have a long form on one page that requires a date, but it can't be a future date, if it is a future date onblur it will give them a error message.


On another page I have a form with a date box that if they enter a past date I want the error message to pop up onblur or it could be onclick.

Thanks so much for your help i was killing my self over it.

Kim
0
ATEN's HDBaseT Presentation at InfoComm 2017

Hear ATEN Product Manager YT Liang review HDBaseT technology, highlighting ATEN’s latest solutions as they relate to real-world applications during her presentation at the HDBaseT booth at InfoComm 2017.

 
LVL 5

Expert Comment

by:Yog
ID: 6148836
oic kim cool - see i have commented the return statements -just remove the comments and call this using a variable. Now it will return 0 if today 1 if greater and -1 if less . Now you can put a if condition and give a alert accordingly, call it in any event .tell me if u wanna code
cheers
0
 

Author Comment

by:kim24
ID: 6148859
Can you help me with the code I am terrible with javascript.............
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149000
Here take a look and see if the functions in this page help:

<html>
<head>
   <title> test for future or past date </title>
<style>
   body {color:darkviolet;background-color:lightseagreen}
   table {background-color:bisque;border:5px double azure}
   input {border:0px solid white;background-color:lightyellow;
          color:peru}
   .dumbcls{color:firebrick;
            border-left:2px inset beige;border-top:2px inset beige;
            border-right:2px inset deepskyblue;border-bottom:2px inset deepskyblue;
            background-color:lightyellow}
   button {color:lightslategray;background-color:peachpuff}
</style>
<script language="JavaScript">
<!--
   var theDate=new Date();
   var theYear=theDate.getYear()*10000
   var theMonth=(theDate.getMonth()+1)*100;
   var theDay=theDate.getDate();
   var today=theYear+theMonth+theDay;
   var excluded =  new Array(0,8,9,16,17,18,37,38,39,40,46);
   function autoTab(fld,len,e)
   {
      var keyCode = e.keyCode;
      if(fld.value.length >= len && !testCode(keyCode))
      {
         fld.value = fld.value.slice(0, len);
         fld.form[(getIndex(fld)+1) % fld.form.length].focus();
      }
      return true;
   }
   function testCode(Kcode)
   {
      var found = false;
      var i = 0;
      while(!found && i < excluded.length)
      if(excluded[i] == Kcode)
         found = true;
      else
         i++;
      return found;
   }
   function getIndex(input)
   {
      var i = -1;
      var j = 0;
      var found = false;
      while (j < input.form.length && i == -1)
      if (input.form[j] == input)
         i = j;
      else
         j++;
      return i;
   }
   function validateDT()
   {
      var x=document.datefield;
      if ((isNaN(x.dtYear.value)) || (isNaN(x.dtMonth.value)) || (isNaN(x.dtDay.value)))
         x.response.value='invalid';
      else
      {
         yy=parseInt(x.dtYear.value)*10000;
         mm=parseInt(x.dtMonth.value)*100;
         dd=parseInt(x.dtDay.value);
         theEntry=yy+mm+dd;
         if (theEntry>today) x.response.value='future';
         if (theEntry<today) x.response.value='past';
         if (theEntry==today) x.response.value='today';
         if ((mm==0) || (mm>1200)) x.response.value='bad month';
      }  
   }
// -->
</script>
</head>
<BODY>
<h1 align="center"> Test an Entered Date for Future or Past</h1>
<p> This accepts a date in the format yyyy mm dd with auto tabbing
    to the fields.  The date formatting can be change to any of the
    numeric formats.  If a text month is used it will require a little
    more script to convert it to a number
</p>
<p> It works very nicely in IE5 but Netscrap would be a real problem.
    The event traps different and I'm not sure which key values have
    to be excluded.  Plus is would look really ugly because the form
    fields will not accept the styling.
</p>
<br>
<form name="datefield">
<table align="center">
<tr>
<td>Enter a Date : <br>
<div class="dumbcls">
<input type="text" name="dtYear"
       onKeyUp="return autoTab(this,4,event);" size="4" maxlength="4">/
<input type="text" name="dtMonth"
       onKeyUp="return autoTab(this,2,event);" size="2" maxlength="2">/
<input type="text" name="dtDay"
       onKeyUp="return autoTab(this,2,event);" size="2" maxlength="2">
</div>
</td>
</tr>
<tr>
<td align="center">
<br>
<button onClick="validateDT()">Validate</button>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="response" size="10" maxlength="10"
       class="dumbcls" readonly><br>
<button onClick="document.datefield.reset()">Reset</button>
</td>
</tr>
</table>
</form>
</body>
</html>


Let me know what additional help you need.

Cd&
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149003
If you need Netscape compatibility we won't be able to do the entry that way, but the basic form handling and test will work if we get rid of the divs in the form

Cd&
0
 

Author Comment

by:kim24
ID: 6149028
COBOLdinosaur, that didn't fuction to good, I also have a long form and the date is just one part of it so I wanted just a popup error to popup if the date was entered incorectly, onblur or something like that, so it pops up right away if they enter a future date.

Thanks.

0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149049
>>>that didn't fuction to good

Is not very specific.  Tell me what didn't work.  Are you getting an error?

What is the format of the date being entered.  You can't just validate it as a number you have to have a specific format.  The one I supplied it but one.

Getting rid of auto tabbing and doing onBlur is not a problem, if I know how the date is formatted.

Cd&
0
 

Author Comment

by:kim24
ID: 6149163
COBOLdinosaur, I just have a regular text box for a date to be typed in. ex..6/2/2001 or 6-2-2001

<input maxLength="12" name="datetest" size="10" >

The problem is it sits in the middle of a form that has over 20 text boxs etc.....  How can I stop someone from entering a future date in this box, and if they do it gives them a popup error right away.

Thanks
Kim
0
 
LVL 9

Expert Comment

by:TTom
ID: 6149231

At the risk of stepping on Cd&'s toes:

<script>
function chkdate(x, dir) {
  mydate = new Date(x)
  today = new Date()
  if ((dir == "future") && (mydate - today < 0)) {alert("Date must be AFTER today's date")}
  if ((dir == "past") && (today - mydate < 0)) {alert("Date must be BEFORE today's date")}
}
</script>
</head>

<input type=text name="AfterToday" onblur="chkdate(this.value,'future');">
<input type=text name="BeforeToday" onblur="chkdate(this.value,'past');">

This obviously needs some tweaking to ensure that the value entered is a valid date )that should not be too hard to do), and you need to do something other than pop up an alert window, but it should work.

FWIW, I would insert something in your form which alerts users as to these constraints.

Tom
0
 
LVL 53

Accepted Solution

by:
COBOLdinosaur earned 400 total points
ID: 6149236
Okay here it is coded for the format m/d/y

To do it for m-d-y change

      dtarr=fldin.split("/");
to
      dtarr=fldin.split("-");

To check for the past date instead of future change:

if (theEntry>today)
to
if (theEntry<today)




<html>
<head>
   <title> test for future or past date </title>
<script language="JavaScript">
<!--
   var theDate=new Date();
   var theYear=theDate.getYear()*10000
   var theMonth=(theDate.getMonth()+1)*100;
   var theDay=theDate.getDate();
   var today=theYear+theMonth+theDay;
   function validateDT()
   {
      var x=document.theform.thefield;
      fldin=new String(x.value);
      dtarr=fldin.split("/");
      mm=dtarr[0];
      dd=dtarr[1];
      yy=dtarr[2];
      yy=parseInt(dtarr[2])*10000;
      mm=parseInt(dtarr[0])*100;
      dd=parseInt(dtarr[1]);
      theEntry=yy+mm+dd;
      if (theEntry>today)
      {
         alert('future date is not permitted');
         x.value='';
         x.focus();
      }  
   }
// -->
</script>
</head>
<BODY>
<form name="theform">
Enter a Date : <br>
<input type="text" name="thefield" onBlur="validateDT()"
       size="10" maxlength="12"><br>
Just another field:<br>
<input type="text" >
</form>
</body>
</html>

Cd&
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149253
>>>At the risk of stepping on Cd&'s toes:

It's better to have company.  Then I have someone else to blame if it doesn't work out. hehe

BTW,

Nice to see you back posting again.

Cd&
0
 

Author Comment

by:kim24
ID: 6149275
COBOLdinosaur I can't get it to validate, test it and see if it works for you

KIm
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149282
I tested it before I posted it in IE 5. what are you putting in that won't validate?

Cd&
0
 

Author Comment

by:kim24
ID: 6149289
I tryed putting the date in every way possible and it took anything it never gave me an error message it just acted like a regular text box?

here is the link that Im testing at
http://64.192.179.29/web/futuredate.cfm
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149320
What you have on that page works perfectly for the format m-d-y

You didn't like the restricted format I posted.  If you want free format dates then you have to specify what the validation rules are.  You either restrict what format the user can enter or it requires detail validation rules to cover all the possibilities like

6/2/2001 and 622001 and 06022001 and 6-2-2001 and 06-02-2001 and jun/02/2001 and 6/2/01 and 6/2,01

As you were already using dates, I assumed you already had basic validation, and just need to handle the specific situations you mentioned.

Cd&
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149325
The difficulty of validating free formatted dates is the reason that meny sites use selects to input dates instead of text fields.

Cd&
0
 

Author Comment

by:kim24
ID: 6149339
Thanks COBOLdinosaur you were right how can i implement those validations in javascript
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149375
For the format you are using (m-d-y) the basic validation that TTOM posted does what you need.

If you need multiple formats then what Yog posted should give you what you need to put it into a common format to pass into the basic validation.

If you are going to be working with formats and validation, you need to start working with the script, or you are not going to be able to maintain your pages.

There is a lot of script posted here you have to adapt it to what you want.

Cd&
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149380
BTW,

In terms of the basic code that best addresses the question, I think TTOM has given you the best response, and you should build on that.

Cd&
0
 

Author Comment

by:kim24
ID: 6149391
COBOLdinosaur, thanks for your help yours did work....  I just tested TTOM and it works great.. I will give you the 100 points and TTOM I will post points for you.

Thanks Guys!!
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 6149397
Glad we could help. Thanks for the A.  :^)

Cd&
0
 
LVL 9

Expert Comment

by:TTom
ID: 6149399
kim24 & Cd&:

Thanks much!  Glad to help.

Been a while since I have had time to hang out here.  Don't know where the time is coming from right now, since I am busier than ever!  Guess I just like feeling useful.

Tom
0
 

Author Comment

by:kim24
ID: 6154244
TTom I posted points for you
0

Featured Post

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Lease-to-own eliminates the expenditure of hardware replacement and allows you to pay off the server over time. Usually, this is much cheaper than leasing servers. Think of lease-to-own as credit without interest.
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question