Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Date checking in Javascript

Posted on 1997-04-16
3
Medium Priority
?
941 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 50 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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…

650 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