Solved

Date checking in Javascript

Posted on 1997-04-16
3
935 Views
Last Modified: 2010-05-18
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
0
Comment
Question by:jgross
[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
  • 2
3 Comments
 
LVL 3

Accepted Solution

by:
RM032397 earned 25 total points
ID: 1265228
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
 

Author Comment

by:jgross
ID: 1265229
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
 

Author Comment

by:jgross
ID: 1265230
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

724 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