View Single Post
  #2 (permalink)  
Old March 29th, 2005, 09:44 AM
joefawcett's Avatar
joefawcett joefawcett is offline
Wrox Author
Points: 9,763, Level: 42
Points: 9,763, Level: 42 Points: 9,763, Level: 42 Points: 9,763, Level: 42
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Exeter, , United Kingdom.
Posts: 3,074
Thanks: 1
Thanked 38 Times in 37 Posts
Default

Here's something to get you started. The date validation is not perfect by any means, as I said before it's a difficult topic. You can easily improve it though by adding to the validateDate function and the other code will not need changing. In a real world application I would use a calendar control to make sure the user entered a valid adate. This also avoids worrying about the fact the format of dates varies form place to place.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Calculate Age</title>
<script type="text/javascript">
function validateDate(DateString)
{
  var oRE = /^\d\d\/\d\d\/\d\d\d\d$/;
  if (oRE.test(DateString))
  {
    var dt = getJsDate(DateString);
    return (dt != null);
  }
  return false;
}

function getJsDate(USDateString)
{
  var arrDtParts = USDateString.split("/");
  try
  {
    var dt =  new Date(arrDtParts[2], (arrDtParts[0] - 1), arrDtParts[1]);
  }
  catch(e)
  {
    return null;
  }
  return dt;
}

function tryCalculateAge(Textbox)
{
  if (validateDate(Textbox.value))
  {
    var iAge = calculateAge(getJsDate(Textbox.value));
    alert(iAge);  
  }
  else
  {
    alert("Invalid date entered. You must submit a date in the format 'mm/dd/yyyy'.");
    Textbox.select();
  }
}

function calculateAge(Birthday)
{
  var dtNow = new Date();
  var iYears = dtNow.getFullYear() - Birthday.getFullYear();
  var iBirthMonth = Birthday.getMonth();
  var iNowMonth = dtNow.getMonth()
  if ( iNowMonth > iBirthMonth)
  {
    return iYears;
  }
  if (iNowMonth < iBirthMonth)
  {
    return iYears - 1;
  }
  var iBirthDate = Birthday.getDate();
  var iNowDate = dtNow.getDate();
  if (iNowDate > iBirthDate)
  {
    return iYears;
  }
  if (iNowDate < iBirthDate)
  {
    return iYears - 1;
  }
  alert("Happy Birthday!");
  return iYears;
}

</script>
</head>
<body>
Enter Birthday (dd/mm/yyyy):#160;<input type="text" size="12" maxlength="10" id="txtBirthday"><br>
<input type="button" onclick="tryCalculateAge(document.getElementById('txtBirthday'));" value="Show Age">
</body>
</html>


--

Joe (Microsoft MVP - XML)
Reply With Quote