Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to validate current date in a form? 3

Status
Not open for further replies.

bricenoej

Programmer
Mar 19, 2002
50
VE
Hi, guys.

Is there a way to validate a current date in a text field?, I mean, the value of the text field (entered by user) must be less than the current day.
 
To make sure the date is less than today...

<script>
function checkDate(){
formField = document.myForm.dateField
passedDate = new Date(formField.value)
if (passedDate == &quot;NaN&quot;){
formField.value = &quot;&quot;
alert(&quot;value is not a date&quot;)
}
else{
now = new Date()
if (passedDate > now){
formField.value = &quot;&quot;
alert(&quot;value is in the future&quot;)
}
else{
theMonth = passedDate.getMonth() + 1
theDate = passedDate.getDate()
theYear = passedDate.getFullYear()
formField.value = theMonth + &quot;/&quot; + theDate + &quot;/&quot; + theYear
}
}
}
</script>

<form name=&quot;myForm&quot;>
<input name=&quot;dateField&quot; onBlur=&quot;checkDate()&quot;>
</form>

Programming today is a race between software engineers striving to build better and bigger idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rick Cook (No, I'm not Rick)

zen.gif
 
I've been having trouble getting this snippet to work. I think the issue is related to the time but it seems to bomb whenever the date is within a day or so (or equal to) today. Essentially all I'm trying to do is check a date input as mm/dd/yyyy and verify that it does not occur before today....

Here's an example:

Code:
<html><head>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkDate(){
    formField = document.Requisition.need_date
    passedDate = new Date(formField.value)
now = new Date()

alert(passedDate);
alert(now);


    if (passedDate == "NaN"){
        formField.value = ""
        alert("value is not a date")
    }
    else{
        now = new Date()

        if (now < passedDate){

            theMonth = passedDate.getMonth() + 1
            theDate = passedDate.getDate()
            theYear = passedDate.getFullYear()
            formField.value = theMonth + "/" + theDate + "/" + theYear

        }
        else{

            formField.value = ""
            alert("The date you selected occurs in the past!")

        }
    }
}
// End hiding -->
</SCRIPT>

</head>
<body>
<FORM NAME="Requisition" ACTION="" METHOD="POST">
	Date Needed (mm/dd/yyyy):&nbsp;<input type="text" name="need_date" length="10" maxlength="10" onchange="checkDate()">
<INPUT TYPE="submit" VALUE="Submit"></center>
</form>
</body></html>

Any ideas? Everything is appreciated! Thanks.

Paul.
 
You might want to try this. I think your problem is in your NaN check.

Code:
function checkDate(){
    formField = document.Requisition.need_date;
    passedDate = new Date(formField.value);
    now = new Date();

    alert(passedDate);
    alert(now);

    if (now < passedDate){
        theMonth = passedDate.getMonth() + 1;
        theDate = passedDate.getDate();
        theYear = passedDate.getFullYear();
        formField.value = theMonth + "/" + theDate + "/" + theYear;
    }
    else{
        formField.value = "";
        alert("Passed Date occurs on or before today");
    }
}

Let me know if this helps.

*cLFlaVA
----------------------------
A polar bear walks into a bar and says, "Can I have a ... beer?"
The bartender asks, "What's with the big pause?
 
I've found that select boxes are a better way to trap dates. It's also easier to verify the dates because you no longer have to test for NaN - just compare the current month, day, and year against the current date. In fact, I'd test the year first - if the year is larger than the current year, there's no need to test the month and day. Then test for current month - if the year test passes, then if the month is larger thatn the current month, no need to test the day. If year and month test pass, then you only have to test for 28 days in February (29 for leap year), 31 days in April, June, September, November.

There's always a better way. The fun is trying to find it!
 
This might be overkill, but it works for me and is very flexible. (should certainly be used in a .js include file and, as comments state, is not my work)
Code:
//     JAVASCRIPT INCLUDE FILE - (c) J R Stockton  >= 2002-11-26
//             [URL unfurl="true"]http://www.merlyn.demon.co.uk/include1.js[/URL]
//       Routines may be copied, but URL must not be linked to.
 var daysallow = 1.5E+339 * 2.4E+317;
 //infinity or so (no limit on how old date can be)
 var daysahead = 0;

// General Utilities :

function LS(x) {return String(x).replace(/\b(\d)\b/g, '0$1')}

function LZ(x) {return(x<0||x>9?"":"0")+x}

function LZZ(x) {return(x<0||x>99?x:"0"+LZ(x))}

if (!String.substr) {
 String.prototype.substr =
  new Function("J", "K", "return this.substring(J, J+K)") }

function TrimS() { // Grant Wagner
 return (this.toString() ? this.toString().replace(/\s+$|^\s*/g, "") : "") }
String.prototype.trim = TrimS

function Sign(y) {return(y>0?'+':y<0?'-':' ')}

function Prepend(Q, L, c) { var S = Q+'' // ??
 // if (!c) var c = ' '
 if (c.length>0) while (S.length<L) { S = c+S } ;
 return S }

function StrU(X, M, N) { // X>=0.0
 var T, S=new String(Math.round(X*Number("1e"+N)))
// if (S.search && S.search(/\D/)!=-1) { return ''+X }
 if (/\D/.test(S)) { return ''+X }
 with (new String(Prepend(S, M+N, '0')))
  return substring(0, T=(length-N)) + '.' + substring(T) }

function StrT(X, M, N) { return Prepend(StrU(X, 1, N), M+N+2, ' ') }

function StrS(X, M, N) { return Sign(X)+StrU(Math.abs(X), M, N) }

function StrW(X, M, N) { return Prepend(StrS(X, 1, N), M+N+2, ' ') }

Number.prototype.toFixed = new Function('n', 'return StrS(this,1,n)') // JL

function SigFigExp(X, N) { // N<22
   if (X==0) return SigFigExp(1, N).replace(/\+1/, ' 0')
   var p = Math.floor(Math.log(Math.abs(X))/Math.LN10)
   if (!isFinite(p)) return X
   return (X>0?'+':'') +
    String(Math.round(X*Math.pow(10, N-p-1))).replace(/(\d)/, "$1.") +
    (p>=0?"e+":"e-") + LZ(Math.abs(p)) } // All OK?


function Div(a, b) { return Math.floor(a/b) }

function Mod(a, b) { return a-Math.floor(a/b)*b }

function Random(N) { return Math.floor(N*(Math.random()%1)) } // as Pascal

var span = Math.pow(2, 32), RandSeed = 0
function SeedRand() { // undertested; different sequence to Math.random()
 return (RandSeed = (134775813*RandSeed + 1) % span )/span }

function Deal(N) { // Numbers 0..(N-1) in random order
 var J, K, A = new Array(N) ; A[0] = 0
 for (J=1; J<N; J++) { K = Random(J+1) ; A[J] = A[K] ; A[K] = J }
 return A }


// end.


// Date/Time Utilities :

function DoWstr(DoWk) { // JS & ISO
 return "SunMonTueWedThuFriSatSun".substr(3*DoWk, 3) }


Date.prototype.ISOlocaltimeStr =
 new Function("with (this) return " +
  "LZ(getHours())+':'+LZ(getMinutes())+':'+LZ(getSeconds())")


Date.prototype.ISOlocaldateStr =
 new Function("with (this) return " +
  "getFullYear()+'-'+LZ(getMonth()+1)+'-'+LZ(getDate())")


Date.prototype.ISOlocalDTstr =
 new Function("with (this) return " +
  "ISOlocaldateStr()+' '+ISOlocaltimeStr()")


Date.prototype.UTCstr =
 new Function("with (this) return " +
  "getUTCFullYear()+'-'+LZ(getUTCMonth()+1)+'-'+LZ(getUTCDate())+' '+ " +
  "LZ(getUTCHours())+':'+LZ(getUTCMinutes())+':'+LZ(getUTCSeconds()) ")


Date.prototype.UTCDstr =
 new Function("with (this) return " +
  "DoWstr(getUTCDay())+', '+UTCstr() ")



Date.prototype.TZstr = // SIGN SHOULD BE RIGHT
 new Function("var X, Y, Z ; with (this) { X=getTimezoneOffset() ; " +
  " Y = Math.abs(X) ; Z = Y % 60 ; Y = (Y-Z)/60 ;" +
  " return (X>0?'-':'+')+LZ(Y)+':'+LZ(Z) }")



function ValidDate(y, m, d) // m = 0..11
 { with (new Date(y, m, d)) return ((getFullYear()==y) && (getMonth()==m)) }

function ReadISO8601date(Q) { var T // adaptable for other layouts
 if ((T = /^(\d+)([-\/])(\d\d)(\2)(\d\d)$/.exec(Q)) == null)
  { return -2 } // bad format
 for (var j=1; j<=5; j+=2) { T[j] = parseInt(T[j], 10) } // wanted ?
 if (!ValidDate(T[1], T[3]-1, T[5])) { return -1 } // bad value
 return [ T[1], T[3], T[5] ] }



if (!String.substr) {
 String.prototype.substr =
  new Function("J", "K", "return this.substring(J, J+K)") }




// MJD 40587 = 1970-01-01 = Javascript day 0. Generally, m is 1..12.

function YMDtoMJD(y, m, d) { return 40587 + (Date.UTC(y, m-1, d)/86400000) }

function MJDtoYMD(MJD) {
 with (new Date((MJD-40587)*86400000)) {
  return [getUTCFullYear(), getUTCMonth()+1, getUTCDate()] }
 /* UTC from 20001115 */ }

function MJDtoISOdow(MJD) { return ((MJD-40587+77777773)%7)+1 } // ISO


function YMDtoYND(y, m, d) { // ISO WkNo. m = 1..12
 var ms1d = 86400000, ms3d=3*ms1d, ms7d=7*ms1d

 var D3=Date.UTC(y,m-1,d)+ms3d
 var wk=Math.floor(D3/ms7d)

 with (new Date(wk*ms7d)) { var yy=getUTCFullYear() }
 return [yy, 1+wk-Math.floor((Date.UTC(yy,0,4)+ms3d)/ms7d),
  ((D3/ms1d)+777777)%7+1] // revised 2001-06-28 for < 1970.

 // for a more general case, alter that "0, 4" and maybe "ms3d"
 }



function UKtaxWN(y, m, d) { // m = 1..12
 var St = 'UK Inland Revenue Tax:'

 var fy = y ; if (m*32+d<134) fy--
 var dd = (Date.UTC(y, m-1, d) - Date.UTC(fy, 3, 6))/86400000
 St += '\nYear ' + fy +
  ', Week ' + LZ(Math.floor(dd/7)+1) + ', Day ' + LZ((dd%7)+1) + ';'

 var yy = y, mm = m
 if (d<6) mm--
 if (mm<4) { yy-- ; mm += 12 }
 St += '\nYear ' + yy + ', Month ' + LZ(mm-3) + '.'

 return St }

function WkNoDtoMJD(Y, N, D) {
 var Jan4 = YMDtoMJD(Y, 1, 4)
 var DoWk = (Jan4+777772)%7
 return Jan4 - DoWk + 7*(N-1) + (D-1)
 }

function JDNtoMJD(YYYY, DDD) {
 return YMDtoMJD(YYYY, 1, 1) + (DDD-1)
 }

function LastSun(y, m, ult) {
 return ult - (YMDtoMJD(y, m, ult)+77777773)%7
 }

function Easter(Yr) {
 // Gregorian, after E G Richards, Algorithm P - upper limit ~ AD 112000?
 var AA = Math.floor(Yr / 100)
 var BB = AA - Math.floor(AA / 4)
 var CC = Yr % 19
 var DD =
  (15 + 19*CC + BB - Math.floor((AA + 1 - Math.floor((AA+8) / 25)) / 3)) % 30
 var EE = DD - Math.floor((CC+11*DD) / 319)
// var S = 22 + EE + (140004 -  Yr - Math.floor(Yr / 4)    + BB - EE) % 7
   var S = 22 + EE + (140004 - (Yr + Math.floor(Yr / 4))%7 + BB - EE) % 7
// Extra %7 greatly increases year range - jrs 20021012
 var EMo = 3 + Math.floor(S / 32)
 var EDy = 1 + (S-1) % 31
 return [EMo, EDy]
 }

function DaysInMonth(Y, M) { // M=1..12   >= 2000-09-01
 with (new Date(Y,M,1,12)) { setDate(0) ; return getDate() } } // OK in NS4?

function leapyear(y)
 { return (new Date(y, 1, 29)).getMonth() == 1 } // F X Mahoney

function Suffix(j) {
 return "thstndrd".substr("01230000000000000000012300000001".charAt(j)*2,2) }

function TimeChangeDates(Y) {
 var Ton, Tof, JanOff, JulOff, TonMin, TonMax, TofMin, TofMax, K
 with(new Date(Y, 00, 01)) {
  TonMin = TofMin = getTime() ; JanOff = getTimezoneOffset()
  setMonth(06) ; JulOff = getTimezoneOffset()
  if (JanOff == JulOff) { return [0,0] }
  setMonth(12) ; TonMax = TofMax = getTime()
  var Min = Math.min(JanOff, JulOff), Max = Math.max(JanOff, JulOff)
  Ton = Tof = (TonMin + TofMax)/2
  for (K=0; K<22; K++) {
   setTime(Ton) ; if (getTimezoneOffset() != Max)
    { TonMax = Ton ; Ton = (TonMin+Ton)/2 }
    else
    { TonMin = Ton ; Ton = (Ton+TonMax)/2 }
   setTime(Tof) ; if (getTimezoneOffset() != Min)
    { TofMax = Tof ; Tof = (TofMin+Tof)/2 }
    else
    { TofMin = Tof ; Tof = (Tof+TofMax)/2 }
   }
  }
 return [Math.round(Ton/60000)*60000, Math.round(Tof/60000)*60000]
 }





// end.


// extract front part of string prior to searchString
function getFront(mainStr,searchStr)
{
     foundOffset = mainStr.indexOf(searchStr)
     if (foundOffset == -1)
     {
          return null
     }
     return mainStr.substring(0,foundOffset)
}

// extract back end of string after searchString
function getEnd(mainStr,searchStr)
{
     foundOffset = mainStr.indexOf(searchStr)
     if (foundOffset == -1)
     {
          return null
     }
     return mainStr.substring(foundOffset+searchStr.length,mainStr.length)
}

// insert insertString immediately before searchString
function insertString(mainStr,searchStr,insertStr)
{
     var front = getFront(mainStr,searchStr)
     var end = getEnd(mainStr,searchStr)
     if (front != null && end != null)
     {
          return front + insertStr + searchStr + end
     }
     return null
}
// remove deleteString
function deleteString(mainStr, deleteStr)
{
     return replaceString(mainStr,deleteStr,"")
}
// replace searchString with replaceString
function replaceString(mainStr, searchStr, replaceStr)
{
     var front = getFront(mainStr, searchStr)
     var end = getEnd(mainStr,searchStr)
     if (front != null && end != null)
     {
          return front + replaceStr + end
     }
     else
     {
          return mainStr
     }
     return null
}


//Date Validation:

// date field validation 
function isDate(gField)
{
     var inputStr = gField.value;
     // convert hyphen delimiters to slashes
     while (inputStr.indexOf("-") != -1)
     {
          inputStr = replaceString(inputStr,"-","/")
     }
     while (inputStr.indexOf(" ") != -1)
     {
          inputStr = replaceString(inputStr," ","/")
     }
     var delim1 = inputStr.indexOf("/")
     var delim2 = inputStr.lastIndexOf("/")
     if (delim1 != -1 && delim1 == delim2)
     {
          // there is only one delimiter in the string
          alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy.  (If the month or date data is not available, enter \'01\' in the appropriate location.)")
          gField.focus()
          gField.select()
          return false
     }
     if (delim1 != -1)
     {
          // there are delimiters; extract component values
          var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
          var mm = parseInt(inputStr.substring(0,delim1),10)
          var yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)
     }
     else
     {
          // there are no delimiters; extract component values
          var dd = parseInt(inputStr.substring(2,4),10)
          var mm = parseInt(inputStr.substring(0,2),10)
          var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
     }
     if (isNaN(mm) || isNaN(dd) || isNaN(yyyy))
     {
          // there is a non-numeric character in one of the component values
          alert("The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: ddmmyyyy, dd/mm/yyyy, or dd-mm-yyyy.")
          gField.focus()
          gField.select()
          return false
     }
     if (mm < 1 || mm > 12)
     {
          // month value is not 1 thru 12
          alert("Months must be entered between the range of 01 (January) and 12 (December).")
          //gField.focus()
          //gField.select()
          return false
     }
     if (dd < 1 || dd > 31)
     {
          // date value is not 1 thru 31
          alert("Days must be entered between the range of 01 and a maximum of 31 (depending on the month and year).")
          gField.focus()
          gField.select()
          return false
     }

     // validate year, allowing for checks between year ranges
     // passed as parameters from other validation functions
     if (yyyy < 100)
     {
          // entered value is two digits, which we allow for 1930-2029
          if (yyyy >= 30)
          {
               yyyy += 1900
          }
          else
          {
               yyyy += 2000
          }
     }

     if (!checkMonthLength(mm,dd))
     {
          gField.focus()
          gField.select()
          return false
     }
     if (mm == 2)
     {
          if (!checkLeapMonth(mm,dd,yyyy))
          {
               gField.focus()
               gField.select()
               return false
          }
     }
	 //check for date range
	 var today = new Date()
     var tmpYYYY = today.getFullYear();
	 var tmpDD = today.getDate();
	 var tmpMM = today.getMonth() + 1;
	 if(tmpMM < 10) tmpMM= "0"+tmpMM;
	 if(mm < 10) mm = "0"+mm;
	 if(tmpDD < 10) tmpDD= "0"+tmpDD;
	 if(dd < 10) dd = "0"+dd;
	 
	 var today = tmpYYYY+"-"+tmpMM+"-"+tmpDD;
	 var otherdate = yyyy+"-"+mm+"-"+dd
	 var diff = DiffDays(otherdate,today);
	 if(diff>daysahead) diff = daysallow +1
	 if (diff<0) diff = diff*(-1);  
	 if(diff > daysallow){
	   alert("Changes must be made within "+daysallow+" days or the date is too far ahead in the future");
       gField.focus()
       gField.select()
       return false
	  }
     return true
}
function monthDayFormat(str)
{
     while (str.length <=2)
     {
          str = "0" + str
     }
     return str
}
// check the entered month for too high a value
function checkMonthLength(mm,dd)
{
     var months = new Array("","January","February","March","April","May","June","July","August","September","October","November","December")
     if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30)
     {
          alert(months[mm] + " has only 30 days.")
          return false
     }
     else
     {
          if (dd > 31)
          {
          alert(months[mm] + " has only 31 days.")
          return false
          }
     }
     return true
}

// check the entered February date for too high a value 
function checkLeapMonth(mm,dd,yyyy)
{
     if (yyyy % 4 > 0 && dd > 28)
     {
          alert("February of " + yyyy + " has only 28 days.")
          return false
     }
     else
     {
          if (dd > 29)
          {
               alert("February of " + yyyy + " has only 29 days.")
               return false
          }
     }
     return true
}


function getDateString()
{
     var dateStr;
     dateStr = "" + this.getFullYear();
     if (this.getMonth() < 9)
          dateStr += "0";
     dateStr += (this.getMonth() + 1);
     if (this.getDate() < 10)
          dateStr += "0";
     dateStr += this.getDate();
     return dateStr;
}
Date.prototype.getDateString = getDateString;
function getFullYear()
{
     var year = this.getYear();
     if (year < 1000)
     {
          year += 1900;
     }
     return year;
}
function DiffDays(S2, S1) {
 var X = ReadISO8601date(S2) ; if (X<0) return "Date 1 bad"
 var Y = ReadISO8601date(S1) ; if (Y<0) return "Date 2 bad"
 return (Date.UTC(X[0], X[1]-1, X[2])-Date.UTC(Y[0], Y[1]-1, Y[2]))/86400000
 }
Date.prototype.getFullYear = getFullYear;
 
WOW.

*cLFlaVA
----------------------------
A polar bear walks into a bar and says, "Can I have a ... beer?"
The bartender asks, "What's with the big pause?
 
Thanks everyone for your help!

cLFlaVA: Your snippet works but has the same problem.... Today is Aug 3rd. If I use "08/03/2004" it still prompts me (i.e. it won't accept it). I need it to take the date 8/3 on (inclusive) and not take the date 8/2 backward. Note that I tried changing the statement [tt]now < passedDate[/tt] to [tt]now <= passedDate[/tt] but that didn't seem to help....

tviman: Great point---I usually like to generate a date selection this way but the particular page I'm using incorporates the excellent DHTML Calendar Widget which is really cool but won't let me configure it for dates before today (that I can figure out anyway).

Nevermoor: Your script looks like the cadillac of date validation but I don't really have a clue how to use it. [blush] I don't suppose you have a really simple example or two somewhere?

Thanks again everyone! Let me know if there's any other ideas---this has to come up a lot for people....
 
Like i said, may be overkill, but it is easy to use.

Just copy the whole think into a .js file,
include the file on the page
(<SCRIPT LANGUAGE=JavaScript SRC='datevaildation.js'></SCRIPT>),
and then you can (at the absolute simplest level) to this:
Code:
if (isDate(form.datefield)){
	form.submit();}
}
 
fpwr

Here's an example script to explain to you what's going wrong with your code (I think)

When you compare 2 dates together, one generated by the new Date constructor's default date of the current date/time, and another by passing a string representation of a date to the date constructor, they will rarely be equal. The reason for this is that when you pass a string representation to the date constructor without specifying a time, it defaults to 00:00:00. Since the times are not even, the date objects are not equal (even though the "dates" are the same). However, if you break apart the date objects and create string representations of the dates, it is easy to compare the 2 and get an accurate answer. I've demonstrated the difference in this sample script:
Code:
<script language=JavaScript>

function dateObjectCheck(str) {
   var today = new Date();
   var str = new Date(Date.parse(str));
   if (str == today) {
      alert("Dates are the same:\n1: " + today + "\n2: " + str);
   }
   else {
      alert("Dates are not the same:\n1: " + today + "\n2: " + str);
   }
}

function dateStringCheck(str) {
   var today = new Date();
   var today = today.getFullYear() + "/" + ((today.getMonth() + 1 < 10) ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1)) + "/" + ((today.getDate() < 10) ? "0" + today.getDate() : today.getDate());
   var str = new Date(Date.parse(str));
   var str = str.getFullYear() + "/" + ((str.getMonth() + 1 < 10) ? "0" + (str.getMonth() + 1) : (str.getMonth() + 1)) + "/" + ((str.getDate() < 10) ? "0" + str.getDate() : str.getDate());
   if (today == str) {
      alert("Dates are the same:\n1: " + today + "\n2: " + str);
   }
   else {
      alert("Dates are not the same:\n1: " + today + "\n2: " + str);
   }
  
}

</script>
<body>
<form name=blahForm>
<input type=text name=blahText value="2004/08/03"><br>
<input type=button value='Check Date Object' onclick='dateObjectCheck(blahForm.blahText.value)'><br>
<input type=button value='Check Date String' onclick='dateStringCheck(blahForm.blahText.value)'>
</form>
</body>
Hopefully that answers your question.

-kaht

banghead.gif
 
fpwr...

I tossed this together for you - it can be as simple or as complicated as you want:

here's the javascript validation routine:
Code:
function testDate(theForm){
 var yr = new Date();
 var currYear = yr.getYear() + 1900;
 var currMonth = yr.getMonth() + 1;
 var currDay = yr.getDate();
 var testyear = theForm.year.options[theForm.year.selectedIndex].value;
 var testmonth = theForm.month.options[theForm.month.selectedIndex].value;
 var testday = theForm.day.options[theForm.day.selectedIndex].value;
 var leap = 4;

 if (theForm.year.selectedIndex == 0){
     alert("Please select a YEAR");
		 theForm.year.focus();
		 return (false);}
 else if (testyear > currYear){
		     alert("Invalid YEAR selection!  Month-Day-Year selection cannot be greater than current date!");
		     return (false);}		 

 if (theForm.month.selectedIndex == 0){
     alert("Please select a MONTH");
		 theForm.month.focus();
		 return (false);}
 else if (testyear >= currYear && testmonth > currMonth){
		     alert("Invalid MONTH selection!  Month-Day-Year selection cannot be greater than current date!");
		     return (false);}
				 
 if (theForm.day.selectedIndex == 0){
     alert("Please select a Day");
		 theForm.day.focus();
		 return (false);}		 
 else if ((testmonth == 4 || testmonth == 6 || testmonth == 9 || testmonth == 11) && testday == 31){
		 alert("Invalid DAY selection.  April, June, September & November have 30 days!");
		 theForm.day.focus();
		 return (false);}
 else if (testmonth == 2 && testyear % leap > 0 && testday > 28){
		 alert("Invalid DAY selection.  February has just 28 days in a non-leap year");
		 theForm.day.focus();
		 return (false);}
 else if (testmonth == 2 && testyear % leap == 0 && testday > 29){
		 alert("Invalid DAY selection.  February has just 29 days in a leap year");
		 theForm.day.focus();
		 return (false);}
 else if (testyear >= currYear && testmonth >= currMonth && testday > currDay){
     alert("Invalid DAY selection!  Month-Day-Year selection cannot be greater than current date!");
		 theForm.day.focus();
		 return (false);}		 
}

And here's some HTML code to play with:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Untitled</title>
<script src="datetest.js" type="text/javascript"></script>
</head>
<body>
<form name="testdate" action="" method="post" onSubmit="testDate(this)">
<select name="month"><option value=""></option><option value="01">Jan</option><option value="02">Feb</option><option value="03">Mar</option><option value="04">Apr</option><option value="05">May</option><option value="06">Jun</option><option value="07">Jul</option><option value="08">Aug</option><option value="09">Sep</option><option value="10">Oct</option><option value="11">Nov</option><option value="12">Dec</option></select>-<select name="day"><option value=""></option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option><
</select>-<select name="year"><option value=""></option><option value="2005">2005</option><option value="2004">2004</option><option value="2003">2003</option><option value="2002">2002</option><option value="2001">2001</option><option value="2000">2000</option><option value="1999">1999</option><option value="1998">1998</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option><option value="1991">1991</option><option value="1990">1990</option></select><p><input type="submit" value="Submit">
</form>
</body>
</html>

There's always a better way. The fun is trying to find it!
 
Just for anyone referencing this thread later, I modified Kaht's excellent "teaching" script to accomplish the original request in one simple file (note that I changed the date format to mm/dd/yyyy):

Code:
<script language=JavaScript>
function dateStringCheck(str) {
   var today = new Date();
   var today = ((today.getMonth() + 1 < 10) ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1)) + "/" + ((today.getDate() < 10) ? "0" + today.getDate() : today.getDate()) + "/" + today.getFullYear();
   var str = new Date(Date.parse(str));
   var str = ((str.getMonth() + 1 < 10) ? "0" + (str.getMonth() + 1) : (str.getMonth() + 1)) + "/" + ((str.getDate() < 10) ? "0" + str.getDate() : str.getDate()) + "/" + str.getFullYear();
   if (today <= str) {
      alert("All is well (Date is greater than or equal to today):\n1: " + today + "\n2: " + str);
   }
   else {
      alert("Bad Date (Date is less than today)!:\n1: " + today + "\n2: " + str);
   }
}
</script>
<body>
<form name=blahForm>
<input type=text name=blahText value="08/04/2004"><br>
<input type=button value='Check Date String' onclick='dateStringCheck(blahForm.blahText.value)'>
</form>
</body>

Thanks everyone for your help! [thumbsup2]

Paul.
 
Sorry one quick (hopefully) followup. When the script above throws the "error" message ("Bad Date"), how would you have the script change the value in the [tt]input[/tt] field back to the original value? Thanks again.
 
fpwr,

Other than saving the original value in a javascript variable, and then setting the field equal to that variable, I can think of no other way. There's no way to call the .reset() method on just one field (that I'm aware of). Also one thing that I had in my example above that should probably be changed:
Code:
   var today = new Date();
   var today = today.getFullYear() + .......
   var str = new Date(Date.parse(str));
   var str = str.getFullYear() + ........
I accidentally used var in front of both of the variable declarations. It should look like this:
Code:
   var today = new Date();
   today = today.getFullYear() + .......
   var str = new Date(Date.parse(str));
   str = str.getFullYear() + ........

-kaht

banghead.gif
 
Can you pass a JS value from one function to another? I was trying to do something like this:

Code:
onchange="saveoriginaldate();dateStringCheck(Requisition.need_date.value)"
 
I was looking at "fpwr"'s code. Can anyone tell me why it doesn't work for a date like '1/10/2006'? The code is included below. Thanks.

<script language=JavaScript>
function dateStringCheck(str) {
var today = new Date();
var today = ((today.getMonth() + 1 < 10) ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1)) + "/" + ((today.getDate() < 10) ? "0" + today.getDate() : today.getDate()) + "/" + today.getFullYear();
var str = new Date(Date.parse(str));
var str = ((str.getMonth() + 1 < 10) ? "0" + (str.getMonth() + 1) : (str.getMonth() + 1)) + "/" + ((str.getDate() < 10) ? "0" + str.getDate() : str.getDate()) + "/" + str.getFullYear();
if (today <= str) {
alert("All is well (Date is greater than or equal to today):\n1: " + today + "\n2: " + str);
}
else {
alert("Bad Date (Date is less than today)!:\n1: " + today + "\n2: " + str);
}
}
</script>
<body>
<form name=blahForm>
<input type=text name=blahText value="08/04/2004"><br>
<input type=button value='Check Date String' onclick='dateStringCheck(blahForm.blahText.value)'>
</form>
</body>
 
I think I fixed that problem. Basically we need to compare the year first. So here's a modified version for anyone who might want to use it later.

function dateStringCheck(str) {
var today = new Date();
var today = today.getFullYear() + "/" +
((today.getMonth() + 1 < 10) ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1)) + "/" +
((today.getDate() < 10) ? "0" + today.getDate() : today.getDate());

var str = new Date(Date.parse(str));

var str = str.getFullYear() + "/" +
((str.getMonth() + 1 < 10) ? "0" + (str.getMonth() + 1) : (str.getMonth() + 1)) + "/" +
((str.getDate() < 10) ? "0" + str.getDate() : str.getDate())

if (today <= str) {
alert("All is well (Date is greater than or equal to today):\n1: " + today + "\n2: " + str);
}
else {
alert("Bad Date (Date is less than today)!:\n1: " + today + "\n2: " + str);
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top