jQuery realizes the simple idea of verifying age

  • 2021-01-02 21:46:00
  • OfStack

This code assumes that the environment is 1 ID "form" for ES2en-ES3en and 3 ID "day", "month", and "year".


$("#age-form").submit(function(){
  var day = $("#day").val();
  var month = $("#month").val();
  var year = $("#year").val();
  var 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){
    alert("Sorry, only persons over the age of " + age + " may enter this site");
    return false;
  }
  return true;
});

You may want to use a more elegant tip than alert. And you should do it again on the server side, or you can only do it on the client side with js enabled.

In any case, the code asks the user to fill in the date of birth, and then calculates whether the user is younger than the site's required age based on the current time.


Related articles: