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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help with datetime validation in javascript 1

Status
Not open for further replies.
Apr 22, 2008
9
US
I found a bunch of examples but they all get a cdate error message. What I'm looking for is if the user puts in something that doesn't resemble a date such as 12345 that it just does an alert box at submit on form validation. The user should be entering a date similar to military datetime such as 4/23/2008 13:29. They will be copy/paste this information from another source.
 
Your easiest solution is to provide hour, minute, year, day, and month dropdown lists, then put the values together in whatever format you like.

Lee
 
Personally, I do it Lee's way in my own applications. However, if you just want something to drop into your page, let the javascript date object do all the work for you:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

function validate(str) {
   var d = new Date(str);
   if (isNaN(d)) {
      alert(str + " could not be recognized as a valid date");
      return false;
   }
   else {
      alert(str + " was recognized as a valid date: " + d);
      return true;
   }
}

</script>

<style type="text/css"></style>

</head>
<body>

<input type="text" id="t" />
<input type="button" value="validate date" onclick="validate(document.getElementById('t').value)" />

</body>
</html>

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Both suggestions will do the trick.

I offer the following only because it catches some additional date errors - and can be used in conjunction with Date object test.

NOTE - It does not validate the timestamp portion.

Based loosely on a forum FAQ ... I enhanced a date validation function for mm/dd/yyyy that catches some wierd errors - which the Date object tolerates.

If you run the self-test section below, you will see the kind of oddball errors it catches.

Here it is FYI with embedded self-testing use cases:


Code:
<script language"javascript">




function WisLeap(year){
    if (year % 4 != 0) {
        return false;
    }
    if (year % 100 != 0){
        return true
    }
    if(year % 400 == 0){
        return false;
    }
}


    
function Wdays_in(month, year){

    var Wmonths = new Array(0,31,28,31,30,31,30,31,31,30,31,20,31) ;

    if ((month<1)  ||  (month>12)) {
        return -1 ; 
    }

    var rtdays  = Wmonths[month] ;
    if (month==2) {
        if(WisLeap(year)) {
               return 29 ;
        }
     }
    return rtdays ;
   
}





//  IsDateOK(myItem)   -   
//
//     DATE VALIDATION  FOR mm/dd/yyyy 
//


//           BASED ON TECHTIPS JAVASCRIPT FORUM FAQ 
//           Date format     checking date format
//           faq216-567      Thanks to SeAL
//           Enhanced by     Friendlyposter
//
//
//   mm - 1 to 12 - 1 digit or 2 digits 
//                - leading space or zero optional before 1 to 9 
//
//
//
//         "1/31/2010"   or "01/31/2010" or " 1/31/2010" 
//
//                   
//
//   dd - 1 to 31 - 1 digit or 2 digits 
//                - leading space or zero optional before 1 to 9 
//
//
//          "12/1/2010"   or "12/01/2010" or "12/ 1/2010" 
//
//
//   dd must be valid for monthe and year specified
//
//
//
//   yyyy - 0001 to 9999 - must be 4 digits 
//
//



    
function IsDateOK(myItem){

    var myDate, myD, myM, myY, myStr, myStr1,  myStr2,  myStr3,  myYearDigit, myMonthDigit, myDayDigit ;

    myStr    = myItem + "" ;

    if(myStr.indexOf('.')>-1) {
        return  false ;
    }

    myDate = myStr.split("/") ;

    if(myDate.length!=3) {
        return  false ;
    }

    myStr1       = myDate[0]    +  "" ;
    myMonthDigit = myStr1.length   ;
    myStr2       = myDate[1]    +  "" ;
    myDayDigit   = myStr2.length   ;
    myStr3       = myDate[2]    +  "" ;
    myYearDigit  = myStr3.length   ;

    if ( (myYearDigit != 4) ||  (myMonthDigit >2) ||  (myDayDigit >2) )  {
        return  false ;
    }
   
    myM          = parseInt(myStr1,10) ;
    myD          = parseInt(myStr2,10) ;
    myY          = parseInt(myStr3,10) ;

    if ( (myM!=myStr1)  ||   (myD!=myStr2)  ||  (myY!=myStr3)  ) {
        return  false ;
    }


    if ( (myY < 1)         || (myD < 1)      
      || (myM < 1)         || (myM > 12)
      || (myD > Wdays_in(myM, myY)) ) {
        return false ;
    } else {
        return true ;
    }


};




//  *** VALIDATION BASED ON DATE OBJECT ALONE

function DATEIsDateOK(str) {
   var d = new Date(str);
   if (isNaN(d)) {
      
      return false;  // invalid date
   }
   else {
      
      return true;  // valid date
   }
}


//  * * *    S E L F    T E S T   S E C T I O N    * * *


//  ** SAMPLE SELF-TEST WITH GOOD AND BAD USE CASES



  var XXbaddates  =  new Array("31/03/2000",   "//2000",      "1/1/2003/2err",   "1/1./2003",     "   ",            
                               "30/0/2020",    "6/0/2060",    "1/1/1",           "9/9/9,999",     "13/1/2000",
                               "0/0/2020",     "6/-6/2060",   "1./1/1",          "90/9/9999",     "13/1.0/2000",
                               "1//2000 ",     "/1/2000",     "02/29/2001",      "31/0/2000",     "3/1/20.0", 
                               "1/1/ 2000 ",   " / / 2000",   "02/29/2009",      "02/29/2000",    "1 / 1 / 2000", 
                               "mm/dd/yyyy",   "",            "00/31/2000",      "04/31/2000",    "6/31/2000", 
                               "09/31/2000",   "0/0/0000",    "1a/1/2003",       "1/1b/2003",     "6/06/2,004",
                               "003/31/2000",  "1/030/0000",  "19/19/1919",      "1/44/2003",     "6/00/2004",
                               "02/29/1600",   "2/29/2005",   "1/1/200a",        "1/32/2003",     "1/001/2004",
                               "1/1/0000",     "-1/1/2000",   "1/1.5/2000",      "1/1/2000.") ;

  var XXgooddates =  new Array("02/29/2004",   "12/31/2000",  "01/31/1999",      "1/1/2000",      "4/14/4444", 
                               "03/31/2010",   "08/31/2020",  "09/30/2030",      "8/1/2040",      "6/30/6666",
                               " 3/31/2010",   " 4/1/2010",   "4/ 2/2010",       "4/ 3/2010",     " 4/ 4/2010",
                               "03/31/2010",   "04/1/2010",   "4/02/2010",       "4/3/2010",      "04/04/2010",
                               "03/30/2010",   "08/11/2020",  "01/30/2030",      "2/29/1604",     "06/30/1900",
                               "10/27/2010",   "02/28/2011",  "2/28/2112",       "2/29/2016",     "06/30/2019",
                               "02/27/2010",   "02/29/0404",  "2/28/0400",       "2/29/0004",     "06/30/0999",
                               "01/29/2051",   "1/1/2002",    "9/9/9999",        "1/1/0001") ;




//  PASS 1 - USING CUSTOM DATE VALIDATION  FOR mm/dd/yyyy


  var XXretvals   =  new Array() ;

  XXretvals[XXretvals.length] = " All Bad Dates s/b False =" ;

  for (var i = 0; i<XXbaddates.length; i++)  {
      var s  = XXbaddates[i] ;
      XXretvals[XXretvals.length] =  IsDateOK(s) ;

  }

  XXretvals[XXretvals.length] = "\n All Good Dates s/b True =" ;

  for (var i = 0; i<XXgooddates.length; i++)  {
      var s  = XXgooddates[i] ;
      XXretvals[XXretvals.length] =  IsDateOK(s) ;

  }

alert(XXretvals) ;




//  PASS 2 - SELF-TEST USING DATE OBJECT VALIDATION ALONE



XXretvals.length=0 ;

  XXretvals[XXretvals.length] = " All Bad Dates s/b False =" ;

  for (var i = 0; i<XXbaddates.length; i++)  {
      var s  = XXbaddates[i] ;
      XXretvals[XXretvals.length] =  DATEIsDateOK(s) ;

  }

  XXretvals[XXretvals.length] = "\n All Good Dates s/b True =" ;

  for (var i = 0; i<XXgooddates.length; i++)  {
      var s  = XXgooddates[i] ;
      XXretvals[XXretvals.length] =  DATEIsDateOK(s) ;

  }

alert(XXretvals) ;





</script>

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top