Solved

Date formatting and validation

Posted on 2001-08-06
16
286 Views
Last Modified: 2012-05-04
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
0
Comment
Question by:chewlf
  • 4
  • 3
  • 3
  • +4
16 Comments
 
LVL 1

Accepted Solution

by:
sureshp earned 25 total points
Comment Utility
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
 

Author Comment

by:chewlf
Comment Utility
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
 
LVL 5

Expert Comment

by:russellshome
Comment Utility

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
 
LVL 5

Expert Comment

by:russellshome
Comment Utility

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
 
LVL 19

Expert Comment

by:webwoman
Comment Utility
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
 
LVL 46

Expert Comment

by:fritz_the_blank
Comment Utility
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
 

Author Comment

by:chewlf
Comment Utility
Hi,
Is anybody know where to get the keycode list?

window.event.keycode

Thanks,
chewlf
0
 
LVL 5

Expert Comment

by:russellshome
Comment Utility
Chewlf, you don't need a list of keycodes.
Suppose e is your event:
var keyChar = String.fromCharCode(e.which);
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:chewlf
Comment Utility
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
 
LVL 5

Expert Comment

by:russellshome
Comment Utility
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
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
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
 
LVL 46

Expert Comment

by:fritz_the_blank
Comment Utility
I recommend a split--there are some fine date validation scripts here.

Fritz the Blank
0
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
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
 
LVL 12

Expert Comment

by:ahosang
Comment Utility
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
 
LVL 46

Expert Comment

by:fritz_the_blank
Comment Utility
Sounds good--not for points but for fairness...

Fritz the Blank
0
 
LVL 5

Expert Comment

by:Netminder
Comment Utility
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now