Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Javascript  date validation

Posted on 2007-08-02
9
Medium Priority
?
231 Views
Last Modified: 2008-01-09
I am writing a javascript function which supposed to format a date as somebody will type in this format XX/XX/XXXX, however it does not work . It does nor insert slashes where they need to be

function checkDate(id) {
       var formfield = document.getElementById(id);
       var label = getLabelForId(id);
       objLenght=formfield.value.lenght;
      
       if (objLenght<=len) return true;
       formfield.value=formfield.value.replace(/\D/g,'');
      objLenght=formfield.value.lenght;
      if (objLenght >=2) formfield.value=formfield.value.replace (/ .{2}/,"$1-");
      if (objLenght >=4) formfield.value=formfield.value.replace (/ .{5}/,"$1-");
      
      
             
       if (isDate(formfield.value) && ((t.getFullYear()-splitDate[2])>15)) {
         label.className = 'completed';
         formfield.style.backgroundColor = "#FFFFFF";
         document.getElementById(id).className = 'form';      
            return true
        
         //document.getElementById(id).className = 'form';  
         //alert('good');
       } else {
         label.className = 'problem';
         Fat.fade_element(id, 60, 300, '#FFFFFF', '#ffd3d3');
        //alert('bad');                         

       }
}
0
Comment
Question by:erikTsomik
  • 3
  • 3
  • 3
9 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 19620759
The problem with removing the non-digits (i.e., "formfield.value.replace(/\D/g,'');") is that then, you have no idea where the separation belongs.

This might help some:
--------------------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Datecheck</title>
<script type='text/javascript'>
  function Two( val ) {
    return ( val < 10 ) ? '0' + val : val;
  }

  function checkDate( field ) {
    var val = field.value;
    if ( val.match( /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) || ( val.match( /(\d{1,2})\/(\d{1,2})\/(\d{2})/ ) ) ) {
      var date = new Date( val );
      var asDate = Two( date.getMonth() + 1 ) + '/' +
                   Two( date.getDate() ) + '/' + date.getFullYear();
      alert( 'Valid date specified: ' + asDate );
      return true;
    } else {
      alert( 'Invalid date specified: ' + val );
      return false;
    }
  }
</script>
</head>
<body onload='document.getElementById("myDate").focus()'>
  <form action=''>
    <table border='1'>
      <tr>
        <td>Date:</td>
        <td><input id='myDate' type='text' onChange='checkDate(this);'></td>
      </tr>
    </table>
  </form>
</body>
</html>
--------------------------------------------------------------------------------
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 19620806
If you want be generous with the supported delimiters, then you could change the date validation regular expressions to be something like:

    if ( val.match( /(\d{1,2})[-.\\/](\d{1,2})[-.\\/](\d{4})/ ) || ( val.match( /(\d{1,2})[-.\\/](\d{1,2})[-.\\/](\d{2})/ ) ) ) {

However, if you do, you need to convert the various non-digits to something that is supported by the Date() constructor using something like:

      val = val.replace( /\D/g, '/' );
0
 
LVL 11

Expert Comment

by:raj3060
ID: 19620848
or you can use this:

<HTML>
<HEAD>
<TITLE>Format Date</TITLE>
<SCRIPT>
function FormatDate(n){
      var m = n.value.toString().replace(/[^0-9.]/g,'')      
      alert(m)
      var saperator = '/'
      if((m.length>0) && (m.length<2)) {
      return m;
      }
      else if(m.length==2){            
            n = m + saperator
            return n;
      }else if((m.length>2) && (m.length<4)){            
            n = m.substring(0,2) + saperator + m.substring(2)
            return n;
      }else if((m.length >=4) && (m.length<=8)){      
            n = m.substring(0,2) + saperator + m.substring(2,4)+ saperator + m.substring(4)
            return n;
      }else if(m.length>8){      
            n = m.substring(0,2) + saperator + m.substring(2,4)+ saperator + m.substring(4,8)
            return n;
      }else{
            return m      
      }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<input type =text name='MENU1' id='MENU1' onkeyup="this.value=FormatDate(this);" maxlength='10' onblur= 'this.value=FormatDate(this);if((this.value.length>0) && (this.value.length<10)){this.value="";alert("Incorrect Date format..")}'/>
<p><INPUT TYPE="button" VALUE="Submit"/></p>
</FORM>
</BODY>
</HTML>
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 19

Author Comment

by:erikTsomik
ID: 19620868
OK. What I am trying to do is apply the formating as I type . XX/XX/XXXX
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 19620884
OK Raj it something like that. Except I do not need all the MSGbox , but this pretty much what I need performing the formating as I type.
0
 
LVL 11

Expert Comment

by:raj3060
ID: 19621757
That message box was just for testing. You can remove that:

or use this:

<SCRIPT>
function FormatDate(n){
      var m = n.value.toString().replace(/[^0-9.]/g,'')      
      var saperator = '/'
      if((m.length>0) && (m.length<2)) {
      return m;
      }
      else if(m.length==2){            
            n = m + saperator
            return n;
      }else if((m.length>2) && (m.length<4)){            
            n = m.substring(0,2) + saperator + m.substring(2)
            return n;
      }else if((m.length >=4) && (m.length<=8)){      
            n = m.substring(0,2) + saperator + m.substring(2,4)+ saperator + m.substring(4)
            return n;
      }else if(m.length>8){      
            n = m.substring(0,2) + saperator + m.substring(2,4)+ saperator + m.substring(4,8)
            return n;
      }else{
            return m      
      }
}
</SCRIPT>

and if you don't want to disaply the other alert when user inputs wrong date then you can remove

alert("Incorrect Date format..") too.

regards
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 19622160
Is this more to your liking?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=7bit">
<title>Datecheck</title>
<script type='text/javascript'>
  function Two( val ) {
    return ( val < 10 ) ? '0' + val : val;
  }

  function checkDate( field ) {
    var val = field.value;
    if ( val.match( /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) || ( val.match( /(\d{1,2})\/(\d{1,2})\/(\d{2})/ ) ) ) {
      val = val.replace( /\D/g, '/' );
      var date = new Date( val );
      var asDate = Two( date.getMonth() + 1 ) + '/' +
                   Two( date.getDate() ) + '/' + date.getFullYear();
      alert( 'Valid date specified: ' + asDate );
      return true;
    } else {
      alert( 'Invalid date specified: ' + val );
      return false;
    }
  }

  function validate( field ) {
    var val = field.value;
    var len = val.length;
    if ( len < 1 ) {
      window.status = 'Begin by entering a two digit month';
    } else if ( len < 2 ) {
      if ( val.match( /\D/ ) ) {
        window.status = 'The month value must be numeric, and two digits in length.  Please try again.';
        field.value = '';
      }
    } else if ( len < 3 ) {
      if ( val.match( /\D/ ) ) {
        window.status = 'The month value must be numeric, and two digits in length.  Please try again.';
        field.value = '';
      } else {
        field.value += '/';
        window.status = 'Day value must be numeric, and two digits in length';
      }
    } else if ( len < 5 ) {
      if ( val.match( /^\d{2}\/\d/ ) ) {
        window.status = 'Day value must be numeric, and two digits in length';
      } else {
        field.value = '';
        window.status = 'Try again';
      }
    } else if ( len < 6 ) {
      if ( val.match( /^\d{2}\/\d{2}/ ) ) {
        field.value += '/';
        window.status = 'Year value must be numeric, and four digits in length';
      } else {
        field.value = '';
        window.status = 'Try again';
      }
    } else if ( ( len > 6 ) && ( len < 10 ) ) {
      if ( val.match( /^\d{2}\/\d{2}\/\d+/ ) ) {
        window.status = 'Year value must be numeric, and four digits in length';
      } else {
        field.value = '';
        window.status = 'Try again';
      }
    } else if ( ( len == 10 ) && ( /^\d{1,2}\/\d{1,2}\/\d{4}$/ ) ) {
      window.status = 'Apparently valid date';
    }
  }
</script>
</head>
<body onload='document.getElementById("myDate").focus()'>
  <form action=''>
    <table border='1'>
      <tr>
        <td>Date:</td>
        <td><input id='myDate' type='text' onkeyup='validate(this)' onChange='checkDate(this);'></td>
      </tr>
    </table>
  </form>
</body>
</html>
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 19624627
Hi raj I like your code. However is that posssible to rewrite your code so it would using id as an inout parameter. Something like this
function checkDate(id) {
       var formfield = document.getElementById(id);
       var label = getLabelForId(id);
0
 
LVL 11

Accepted Solution

by:
raj3060 earned 2000 total points
ID: 19627203
Yes:

function FormatDate(id){
      var m = document.getElementById(id).value.toString().replace(/[^0-9.]/g,'')    
   .....
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
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…
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…
Suggested Courses

572 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