Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 296
  • Last Modified:

Date javascript

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
kim24
Asked:
kim24
  • 11
  • 9
  • 3
  • +1
1 Solution
 
YogCommented:
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
 
YogCommented:
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
 
kim24Author Commented:
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
YogCommented:
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
 
kim24Author Commented:
Can you help me with the code I am terrible with javascript.............
0
 
COBOLdinosaurCommented:
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
 
COBOLdinosaurCommented:
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
 
kim24Author Commented:
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
 
COBOLdinosaurCommented:
>>>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
 
kim24Author Commented:
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
 
TTomCommented:

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
 
COBOLdinosaurCommented:
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
 
COBOLdinosaurCommented:
>>>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
 
kim24Author Commented:
COBOLdinosaur I can't get it to validate, test it and see if it works for you

KIm
0
 
COBOLdinosaurCommented:
I tested it before I posted it in IE 5. what are you putting in that won't validate?

Cd&
0
 
kim24Author Commented:
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
 
COBOLdinosaurCommented:
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
 
COBOLdinosaurCommented:
The difficulty of validating free formatted dates is the reason that meny sites use selects to input dates instead of text fields.

Cd&
0
 
kim24Author Commented:
Thanks COBOLdinosaur you were right how can i implement those validations in javascript
0
 
COBOLdinosaurCommented:
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
 
COBOLdinosaurCommented:
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
 
kim24Author Commented:
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
 
COBOLdinosaurCommented:
Glad we could help. Thanks for the A.  :^)

Cd&
0
 
TTomCommented:
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
 
kim24Author Commented:
TTom I posted points for you
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 11
  • 9
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now