JavaScript: Age Validation Form

Published on Author craigzearfossLeave a comment

This form validates the date selected by the user is valid and that the user is at least the age of 18. (Note that it does not dynamically adjust the day select list based on the month and year selected.)

HTML

<form id="age-validation-form" class="form-inline" method="POST">
  <div class="form-group">
    <select name="dob_month" id="dob_month" class="required form-control">
      <option value="">Month</option>
      <option value="1">January</option>
      <option value="2">February</option>
      <option value="3">March</option>
      <option value="4">April</option>
      <option value="5">May</option>
      <option value="6">June</option>
      <option value="7">July</option>
      <option value="8">August</option>
      <option value="9">September</option>
      <option value="10">October</option>
      <option value="11">November</option>
      <option value="12">December</option>
    </select>
  </div>
  <div class="form-group">
    <select name="dob_day" id="dob_day" class="required form-control">
      <option value="">Day</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10">10</option>
      <option value="11">11</option>
      <option value="12">12</option>
      <option value="13">13</option>
      <option value="14">14</option>
      <option value="15">15</option>
      <option value="16">16</option>
      <option value="17">17</option>
      <option value="18">18</option>
      <option value="19">19</option>
      <option value="20">20</option>
      <option value="21">21</option>
      <option value="22">22</option>
      <option value="23">23</option>
      <option value="24">24</option>
      <option value="25">25</option>
      <option value="26">26</option>
      <option value="27">27</option>
      <option value="28">28</option>
      <option value="29">29</option>
      <option value="30">30</option>
      <option value="31">31</option>
    </select>
  </div>
  <div class="form-group">
    <select name="dob_year" id="dob_year" class="required form-control">
      <option value="">Year</option>
    </select>
  </div>
  <button type="submit">Submit</button>
</form>
<p class="error bg-danger">Sorry, you must be 18 years old or older to view this content.</p>

CSS includes

.error.bg-danger.hide {
    display: none;
}
.error.bg-danger.show {
    display: block;
}

JavaScript includes

<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.2/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>

JavaScript code

<script>

$().ready(function() {

  // populate the year select list
  var thisYear = new Date().getFullYear();
  var firstYear = thisYear - 100;
  var yearOptions = "";
  for (var year = firstYear; year <= thisYear; year++) {
    if ($("#dob_year option[value='" + year + "']").length == 0) {
      $("#dob_year").append($("<option />").val(year).html(year));
    }
  }

  // append url parameter onto the form action
  $("form").attr("action", $("form").attr("action") + location.search);

});

function isOfAge(year, month, day, age) {
  age = age || 18;

  var mydate = new Date();
  mydate.setFullYear(year, month-1, day);

  var currdate = new Date();
  currdate.setFullYear(currdate.getFullYear() - age);
  if ((currdate - mydate) < 0){
    return false;
  }
  return true;
}

function isValidDate(year, month, day) {

  // Create list of days of a month [assume there is no leap year by default]
  var listofDays = [31,28,31,30,31,30,31,31,30,31,30,31];

  if (month == 1  || month > 2) {

    if (day > listofDays[month - 1]) {
      // invalid date
      return false;
    }

  }

  if (month == 2) {

    var lyear = false;

    if ((!(year % 4) && year % 100) || !(year % 400)) {
      lyear = true;
    }

    if ((lyear == false) && (day >= 29)) {
      // invalid date (February - non-leap year)
      return false;
    }
  
    if ((lyear == true) && (day > 29)) {
      // invalid date (February - leap year)
      return false;
    }
  }

  return true;
}

(function($,W,D)
{
  var JQUERY4U = {};

  JQUERY4U.UTIL =
  {
    setupFormValidation: function() {
      //form validation rules
      $("#age-validation-form").validate({
        rules: {
          dob_month: "required",
          dob_day: "required",
          dob_year: "required"
        },
        messages: {
          dob_month: "Please select a month",
          dob_day: "Please select a ",
          dob_year: "Please select a year"
        },
        submitHandler: function(form) {
          if (!isValidDate($("#dob_year").val(), $("#dob_month").val(), $("#dob_day").val())) {
            // make sure the date is valid
            $("#error-message").html("The date is not valid.").removeClass("hide").addClass("show");
            return false;
          } else if (!isOfAge($("#dob_year").val(), $("#dob_month").val(), $("#dob_day").val(), 18)) {
            // the person is too young
            $("#error-message").html("Sorry, you must be 18 years old or older to view this content.").removeClass("hide").addClass("show");
            return false;
          } else {
            $("#error-message").removeClass("show").addClass("hide");
            form.submit();
            return true;
          }
        }
      });
    }
  }

  //when the dom has loaded setup form validation rules
  $(D).ready(function($) {
    JQUERY4U.UTIL.setupFormValidation();
  });

})(jQuery, window, document);

</script>

References:

Leave a Reply

Your email address will not be published. Required fields are marked *