Date checking in Javascript

I was looking for a Javascript method/function that could do the equivalent of ISDATE from VBScript.  Basically, I just wanted to be able to check in a form if a user has entered a valid date- for example, February 31 would give you an error message.

I had looked around a number of Javascript sites with no luck.

Any help is greatly appreciated.

Thanks in advance,
Jason Gross
jgross@tact.com
jgrossAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RM032397Commented:
Takes a fair bit of code!
Here is a demo for a particular format, adaptable for the format you choose:
=============================================================
<HTML><HEAD><TITLE>Validation of a date</TITLE>

<SCRIPT LANGUAGE="JavaScript">
// Copyright Rodney Myers rmyers@patrol.i-way.co.uk
// Script may be used and adapted with these lines intact
// Original script at http://www.catalog.co.uk/demo/game/datevali.htm
// Other demos at http://www.catalog.co.uk/demo/game/

// global vars
var errfound = false
//FORM VALIDATION FUNCTIONS

// display an error alert
function error(elem,ShowName, text) {
// abort if we already found an error
   if (errfound)  return;
   elem.focus();
   elem.select();
   PopupError(ShowName, text);
   errfound = true;
}

// main validation function
function Validate(form) {
   errfound = false;
   datecheck(form.date1,"Date1")
   return !errfound; /* true if there are no errors */
}


function datecheck(elem,Show) { // already passed for length == 9
var Message = ""
var OK = true
var Instr = elem.value
var Mpart = Instr.substring(0,3).toUpperCase()
var Dinst = Instr.substring(3,5)
var Dpart = parseInt("1"+Dinst) - 100
var Yinst = Instr.substring(5,9)
var Ypart = parseInt("1"+Yinst) - 10000
// alert("MMM : " + Mpart)
// alert("dd  : " + Dinst)
// alert("YYYY: " + Yinst)
if (Instr.length < 9) {Message += "<BR>Input is too short ! (" + Instr + ")<BR>" ; OK = false }
if (Instr.length > 9) {Message += "<BR>Input is too long ! (" + Instr + ")<BR>" ; OK = false }


if (foundin("JAN.FEB.MAR.APR.MAY.JUN.JUL.AUG.SEP.OCT.NOV.DEC" , Mpart) == -1 )
   {Message+= "Month part incorrect : (" + Mpart + ")<BR>" ; OK = false}


if (!OK && !( Dpart>0 && Dpart <= 31))
   {Message+= "Day part incorrect : (" + Dinst + ")<BR>" ; OK = false}
else
   {
   if ((foundin("JAN.MAR.MAY.JUL.AUG.OCT.DEC",Mpart) > -1 && !( Dpart>0 && Dpart <= 31))
   ||(foundin("APR.JUN.SEP.NOV",Mpart) > -1 && !( Dpart>0 && Dpart <= 30))
   ||(Mpart == "FEB" && !(Dpart>0 && Dpart <= (28 + leapYear(Ypart)   ) )) )
   {Message+= "Day part incorrect : (" + Dinst + ")<BR>" ; OK = false}
   }

if ( leapYear(Ypart) == 0  && Dpart == 29 ) Message+= (Ypart + " is not a Leap Year.<BR>" )

if (!( Ypart>1900 && Ypart <= 2050))
   {Message+= "Year part incorrect : (" + Yinst + ")<BR>" ; OK = false}
   
if (!OK) error(elem,Show,"You have entered \"" + elem.value  + "\"<BR>Please enter in the MMMddyyyy format<BR>eg JAN031999<BR><BR>"+Message )
}

// From Gordon McComb's JavaScript Sourcebook (Wiley)
function leapYear (Year) {
      if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0))
            return (1);
      else
            return (0);
}


function foundin(Target,S){
var Ret = false;
var Pos = -1;
if (S.length==0) return (-1);
 for ( var N=0 ; N<Target.length-S.length +1 ; N++ )
      { Temp = Target.substring(N,N+S.length);
if ( S == Target.substring(N,N+S.length)) {Pos = N; break} }
return(Pos)
}


function PopupError(Item,Message) {
// Create the popup window.
//
   var Options = "toolbar=0,location=0,directories=0,status=0,menubar=0," +
                 "scrollbars=0,resizable=1,width=450,height=350";
   PopUp = window.open("", "", Options);
//
// Write to the the window.
//
   PopUp.document.open();
   PopUp.document.writeln("<HTML><HEAD><TITLE>Just checking the information you input ...</TITLE>");
   PopUp.document.writeln("<BODY Bgcolor='#00BFFF'><CENTER>");
   PopUp.document.writeln("<H2>About your "+Item+"</H2>");
   PopUp.document.writeln("<P>" + Message + "<P><FORM>");
   PopUp.document.writeln("<INPUT Type='button' Value=' OK ' " +
                          "onClick='self.close()'>");
   PopUp.document.writeln("</FORM></CENTER></BODY></HTML>");
   PopUp.document.close();
}; // end

</SCRIPT>
</HEAD>
<body>
<P>The validation function is set to validate any number of fields, with tests placed in the function and calls to an error function which sends a validation message for the first field found with an error.<BR><BR>
Once that field passes validation, subsequent fields may trigger an alert. Anyway there is only one field here, but the apparatus is there for extension.<BR><BR>
The MMMddyyyy format is not my choice, but was requested on news:comp.lang.javascript. A little adjustment would make validation for, say, ddMMMyyyy OR ddMMMyy OR yyyyMMMdd quite easily possible.<BR><BR>
Month lengths are taken into account including February in and out of leap years using Gordon McCombs leapYear() function.<BR></P>

<FORM NAME="dates">
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="2">
<TR><TD>Input date (date1)</TD><TD><INPUT TYPE="TEXT" NAME="date1" VALUE="MMMddyyyy"></TD></TR>
<TR><TD></TD><TD><INPUT TYPE="BUTTON" VALUE="Validate" ONCLICK="Validate(this.form)"></TD></TR>
</TABLE>
</FORM>
</BODY></HTML>

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jgrossAuthor Commented:
It looks good but I received two JS errors:

line 66: undetermined string literal.
         if ( leapYear(Ypart) == 0 && Dpart == 29 ) Message+= (Ypart + " is not a Leap
.........^

line 67: missing ) in parenthetical
        Year.<BR>" )
........^



0
jgrossAuthor Commented:
It looks good but I received two JS errors:

line 66: undetermined string literal.
         if ( leapYear(Ypart) == 0 && Dpart == 29 ) Message+= (Ypart + " is not a Leap
.........^

line 67: missing ) in parenthetical
        Year.<BR>" )
........^



0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.