Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Date formatting and validation

Posted on 2001-08-06
16
Medium Priority
?
301 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
[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
  • 4
  • 3
  • 3
  • +4
16 Comments
 
LVL 1

Accepted Solution

by:
sureshp earned 100 total points
ID: 6355210
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
ID: 6355232
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
ID: 6355269

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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 5

Expert Comment

by:russellshome
ID: 6355277

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
ID: 6355632
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
ID: 6355815
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
ID: 6357715
Hi,
Is anybody know where to get the keycode list?

window.event.keycode

Thanks,
chewlf
0
 
LVL 5

Expert Comment

by:russellshome
ID: 6359340
Chewlf, you don't need a list of keycodes.
Suppose e is your event:
var keyChar = String.fromCharCode(e.which);
0
 

Author Comment

by:chewlf
ID: 6362328
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
ID: 6367601
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
ID: 7955633
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
ID: 7956217
I recommend a split--there are some fine date validation scripts here.

Fritz the Blank
0
 
LVL 12

Expert Comment

by:ahosang
ID: 7956723
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
ID: 7998816
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
ID: 8001204
Sounds good--not for points but for fairness...

Fritz the Blank
0
 
LVL 5

Expert Comment

by:Netminder
ID: 8077924
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

722 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