-2

When I tab, the result putted in the textbox was NaN. While in my computer at home, it outputs a number. Please help.

function ageCount() {
  var date1 = new Date();
  var dob = document.getElementById("dob").value;
  var date2 = new Date(dob);
  var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;

  if (pattern.test(dob)) {
    var y1 = date1.getFullYear();
    //getting current year            
    var y2 = date2.getFullYear();
    //getting dob year            
    var age = y1 - y2;
    //calculating age                       
    document.getElementById("ageId").value = age;
    document.getElementById("ageId").focus ();
    return true;
  } else {
    alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
    return false;
  }
}
Dancrumb
  • 26,597
  • 10
  • 74
  • 130

2 Answers2

0

If you pass an invalid date string to Date, you get an invalid Date.

(new Date("9999-99-99"))

If you call getFullYear on an invalid Date, you get NaN.

If you try to perform any arithmetic operations on NaN, you get Nan.

So, your problem is that you tabbed out of you input box and it was empty and this is what was passed to Date in your line:

var date2 = new Date(dob);

You should improve your pattern to eliminate any invalid date.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130
0

If you really do search for dd/mm/yyyy date format, then your pattern should be

/^\d{1,2}\/\d{1,2}\/\d{4}$/


Notice : You're not actually calculating age but the difference between year of birth and current year. If one's birthday occurs after current date, it will one year wrong. You could look at this response for a good starting point on building this calculator.

Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285