Date formatting and validation

Can somebody help me on this?

If the date has been typed into the textbox with any format, how to autoformat it to 'DD Mon YYYY' and at the same time trigger the validation to pop up message if wrong format has been typed?

Pls help.

Thanks,
chewlf
chewlfAsked:
Who is Participating?
 
sureshpConnect With a Mentor Commented:
chewlf,

Give input as 01/01/2001.
Hope this will solve your problem. Just cut and paste.
<html>
<head>

<script language=javascript>
function IsValidDate(val) {

   var str,re,match,s,d;
   
   str = val;
   re = /(\d+)\/(\d+)\/(\d{2,4})/;
   match = re.exec(str);
   if (match.length < 4) return false;  // didn't fit mask // Suresh kumar P

   // Check if it was actually a valid date
   for (var i=1;i<=3;i++) match[i] = parseInt(match[i]);
    if(match[3]<1000)
  {
  alert("wrong");
  }
  else
  {
   
  }
   str = match[1] + "/" + match[2] + "/" + match[3];
   var d = new Date(str);
   return (d.getDate() == match[2]) && ((d.getMonth()+1) == match[1]) && (d.getFullYear() == match[3]);
}
</script>

</head>
<body>
<form name=myform>
date <input type=text name=date>
<input type=button value="Check Date" onClick="alert(IsValidDate(document.myform.date.value))">
</form>
</body>
</html>  
0
 
chewlfAuthor Commented:
Hi,
Thanks for your help but it didn't meet the requirement. Below is a sample that I got. I need some help to modify it so that it can be autoformatted to "DD Mon YYYY" instead of "DD/MM/YY".

<HTML>
<HEAD>
<TITLE>Autoformatting of Date and Valid Date Check</TITLE>
<SCRIPT LANGUAGE="Javascript">

function FormatDate(i, delKey,direction) {
  if (i.value.length < 10) {
       if (delKey!=9) { //tab
            if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41)){ //if the delete, backspace, shift, are not the keys that caused the keyup event.
                 var fieldLen = i.value.length
                  if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) {
                       if (fieldLen == 2 || fieldLen == 5) {
                          i.value = i.value + "/";
                    }
                  } else {
                       if (direction == "up") {
                         if (i.value.length == 0) {
                               i.value = ""
                         } else {
                               i.value = i.value.substring(0,i.value.length-1)
                            }
                   }
                }
                 i.focus()
            }
      } else {
           if (direction == "down") {
                CheckDate(i)
            }
       }
 }
}
function CheckDate(THISDATE) {
     var err=0
     a=THISDATE.value
     if (a.length != 10) err=1
     b = a.substring(0, 2)// month
     c = a.substring(2, 3)// '/'
     d = a.substring(3, 5)// day
     e = a.substring(5, 6)// '/'
     f = a.substring(6, 10)// year
     if (b<1 || b>12) err = 1
     if (d<1 || d>31) err = 1
     if (f<1900) err = 1
     if (b==4 || b==6 || b==9 || b==11){
          if (d==31) err=1
     }
     if (b==2){
          var g=parseInt(f/4)
          if (isNaN(g)) {
               err=1
          }
          if (d>29) err=1
          if (d==29 && ((f/4)!=parseInt(f/4))) err=1
     }
     if (err==1) {
          alert(THISDATE.value + ' is not a valid date. Please re-enter.');
          THISDATE.value = ""
     }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="DateCheck"><INPUT TYPE=text onchange="CheckDate(this)" onkeydown="FormatDate(this, window.event.keyCode,'down')" onkeyup="FormatDate(this, window.event.keyCode,'up')">
<BR>
<BR>
Watch as you type the date format itself<BR>
OnBlur it will check to verify it's a valid date
</BODY></HTML>
0
 
russellshomeCommented:

Use selectors to make sure the user is unable to enter an invalid date.

There is no way to ensure the date is interpreted correctly when using a textbox. Here in NZ we use DD/MM/YY but in the USA MM/DD/YY. There is no way to tell whether 01/04/01 is 1st Apr 2001 or 4th Jan 2001.

Use onChange on the Month and Year selector to set the day selector to have the correct number of options:

/*
     @param iMonth Month of the year (1=Jan 12=Dec)
     @param iYear 4 digit year
*/
function daysInMonth(iMonth, iYear) {
 var dTemp = new Date(iYear, iMonth, 1)
 var dTemp2 = new Date(dTemp.valueOf() - 1)
 return dTemp2.getDate()
}

function setDayOptions(objSelector, iMonth, iYear) {
 for (var i=1;i<=daysInMonth(iMonth, iYear); i++) {
  objSelector.options[i-1] = new Option(i, i)
 }
}
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
russellshomeCommented:

Use selectors to make sure the user is unable to enter an invalid date.

There is no way to ensure the date is interpreted correctly when using a textbox. Here in NZ we use DD/MM/YY but in the USA MM/DD/YY. There is no way to tell whether 01/04/01 is 1st Apr 2001 or 4th Jan 2001.

Use onChange on the Month and Year selector to set the day selector to have the correct number of options:

/*
     @param iMonth Month of the year (1=Jan 12=Dec)
     @param iYear 4 digit year
*/
function daysInMonth(iMonth, iYear) {
 var dTemp = new Date(iYear, iMonth, 1)
 var dTemp2 = new Date(dTemp.valueOf() - 1)
 return dTemp2.getDate()
}

function setDayOptions(objSelector, iMonth, iYear) {
 for (var i=1;i<=daysInMonth(iMonth, iYear); i++) {
  objSelector.options[i-1] = new Option(i, i)
 }
}
0
 
webwomanCommented:
go to www.javascriptsource.com and check out their scripts. They have one that does almost exactly what you want. You might need to modify it a little, but it works very well.
0
 
fritz_the_blankCommented:
I have been using the following (based on a question that was answered elsewhere in EE) where lclObject is the date field and lclMessage fills in the contents of the alert:

function checkDate(lclObject, lclMessage)
{
     var value =""
     value = eval("document.form1." + lclObject + ".value")
     
     if(value.length>0)
          {
             var dateregex=/^[ ]*[0]?(\d{1,2})\/(\d{1,2})\/(\d{4,})[ ]*$/;
              var match=value.match(dateregex);
              if (match)
               {
                        var tmpdate=new Date(match[3],parseInt(match[1])-1,match[2]);
                   if (tmpdate.getDate()==parseInt(match[2]) && tmpdate.getFullYear()==parseInt(match[3]) && (tmpdate.getMonth()+1)==parseInt(match[1]))
                    {
                    return false;
                    }
                   }
          alert(Message: The " + lclMessage + " must be a valid date in the format MM/DD/YYYY");
          eval('document.form1.' + lclObject + ".focus()");
          return true;
          }
     else
          {
          return false;
          }
}
0
 
chewlfAuthor Commented:
Hi,
Is anybody know where to get the keycode list?

window.event.keycode

Thanks,
chewlf
0
 
russellshomeCommented:
Chewlf, you don't need a list of keycodes.
Suppose e is your event:
var keyChar = String.fromCharCode(e.which);
0
 
chewlfAuthor Commented:
Hi russellshome,
Can you explain more on this? I don't get what you mean. Maybe you can give me the source where I can test out this. Thanks.
0
 
russellshomeCommented:
Source code example (directly from Manual at developer.netscape.com)

function Key_Up(e) {
 var keyChar = String.fromCharCode(e.which);
 alert("Hold '" + keyChar +"' again for me, okay?");
}
document.onkeyup=Key_Up;
document.captureEvents(Event.KEYUP);
0
 
ahosangFinance Systems DeveloperCommented:
This question has been abandoned. I will make a recommendation to the moderators on its resolution in a week or two. I appreciate any comments that would help me to make a recommendation.
 
In the absence of responses, I may recommend DELETE unless it is clear to me that it has value as a PAQ. Silence = you don't care
ahosang
EE cleanup volunteer
0
 
fritz_the_blankCommented:
I recommend a split--there are some fine date validation scripts here.

Fritz the Blank
0
 
ahosangFinance Systems DeveloperCommented:
can split two ways at most due to the low value of the question and the directive of Netminder. Any idea which two best??
0
 
ahosangFinance Systems DeveloperCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

SPLIT (sureshp/fritz_the_blank)
Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

ahosang
EE Cleanup Volunteer
0
 
fritz_the_blankCommented:
Sounds good--not for points but for fairness...

Fritz the Blank
0
 
NetminderCommented:
Per recommendation, force-accepted.

Netminder
EE Admin

fritz_the_blank: points for you at http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20540453.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.