Date validator

by Noemi Totos

HTML

<input type="text" value="" placeholder="DD" name="customer[dob]" id="dob_day" class="large" /> /
<input type="text" value="" placeholder="MM" name="customer[dob]" id="dob_month" class="large" /> /
<input type="text" value="" placeholder="YYYY" name="customer[dob]" id="dob_year" class="large" />
<button class="btn" type="submit" value="isValidDate">Validate</button>

JavaScript

$(".btn").on ('click', function(dateString) {
  // Combine date
  var day = $('#dob_day').val();
  var month = $('#dob_month').val();
  var year = $('#dob_year').val();
  var dateString = day + "/" + month + "/" + year;
  console.log(dateString);

  // First check for the pattern
  if (!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(dateString)) {
    return false;
    console.log('false pattern');
  }

  // Parse the date parts to integers
  var parts = dateString.split("/");
  var day = parseInt(parts[0], 10);
  var month = parseInt(parts[1], 10);
  var year = parseInt(parts[2], 10);

  // Check the ranges of month and year
  if (year < 1911 || year > 2011 || month == 0 || month > 12) {
    return false;
    console.log('incorrect month/year ranges');
  }

  var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  // Adjust for leap years
  if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
    monthLength[1] = 29;

  // Check the range of the day
  return day > 0 && day <= monthLength[month - 1];
});