Question : Problem with format date javascript

I have the javascript below which formats a date to mm/dd/yyyy format. It works fine when user enters a date (onblur), the problem is many times the field is not required and user tabs through it and if user doesnt enter anything I get a javascript error

Script:

 <script language="javascript">
        function reformatAndValidate(field) {
  var str = field.value;
var parts = str.replace(/\/|\-|\:/g, " ").split(" "); // change - or / or : to spaces
  var year = (parts[2].length==4)?parts[2]:parseInt(parts[2],10)+2000;
var month = parseInt(parts[0],10); // change to parts[1]; if d/m/y
 var date = parseInt(parts[1],10);  // change to parts[0]; if d/m/y
  var testDate = new Date(year, month-1, date);
  if (testDate.getDate() != date || testDate.getMonth() != (month-1)) {
    field.value=str +' is invalid';
    return false
  }
  if (month<10) month = "0"+month;
  if (date<10) date = "0"+date;
  field.value = ""+month+"/"+date+"/"+year;
  return true;
}

</script>

object has:

onBlur="mark(this,'#FFFFFF','#000000');reformatAndValidate(this);"

And the error is:

2.lenght is null or not an object

Answer : Problem with format date javascript

Line 4:

if (str=="") { return true; } // empty string is ok
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
 <script language="javascript">
        function reformatAndValidate(field) {
var str = field.value;
if (str=="") { return true; } // empty string is ok
var parts = str.replace(/\/|\-|\:/g, " ").split(" "); // change - or / or : to spaces
if (parts.length<3) { // not enough parts
    field.value=str +' is invalid';
    return false;
}
var year = (parts[2].length==4)?parts[2]:parseInt(parts[2],10)+2000;
var month = parseInt(parts[0],10); // change to parts[1]; if d/m/y
 var date = parseInt(parts[1],10);  // change to parts[0]; if d/m/y
  var testDate = new Date(year, month-1, date);
  if (testDate.getDate() != date || testDate.getMonth() != (month-1)) {
    field.value=str +' is invalid';
    return false
  }
  if (month<10) month = "0"+month;
  if (date<10) date = "0"+date;
  field.value = ""+month+"/"+date+"/"+year;
  return true;
}

</script>
Random Solutions  
 
programming4us programming4us