Javascript date validation

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');                         

       }
}
LVL 19
erikTsomikSystem Architect, CF programmer Asked:
Who is Participating?
 
raj3060Commented:
Yes:

function FormatDate(id){
      var m = document.getElementById(id).value.toString().replace(/[^0-9.]/g,'')    
   .....
0
 
HonorGodSoftware EngineerCommented:
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
 
HonorGodSoftware EngineerCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
raj3060Commented:
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
 
erikTsomikSystem Architect, CF programmer Author Commented:
OK. What I am trying to do is apply the formating as I type . XX/XX/XXXX
0
 
erikTsomikSystem Architect, CF programmer Author Commented:
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
 
raj3060Commented:
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
 
HonorGodSoftware EngineerCommented:
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
 
erikTsomikSystem Architect, CF programmer Author Commented:
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
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.