0

My form page (HTML) needs user's DOB. And the format is: dd-mm-yyyy and the data type is in text. e.g. April 21st, 1990 is 21-04-1990. My assignment requires that user has to be older than 18 but cannot older be than 80.

My Javascript needs to read user's input and calculate current date minus user's input to check if age qualifies.

I expect the output of DOB to allow or restrict the form's page.

Age = Current Date - User's DOB If 18 or older go to the next page, deny if less than 18. If 80 or older, cannot advance to next page.

SFN
  • 1
  • 1
    You're asking two questions in one: how to [*parse a date formatted as dd-mm-yyyy*](https://stackoverflow.com/search?q=%5Bjavascript%5D+parse+dd-mm-yyyy) and [*how to calculate age from a date*](https://stackoverflow.com/search?q=%5Bjavascript%5D+calculate+age). Both have been answered many times before. What have you tried? Where did it go wrong? – RobG Apr 21 '19 at 11:46

1 Answers1

0

Regarding changing the format of the date please read here

   function get_age(born, now) {
      var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());
      if (now >= birthday) 
        return now.getFullYear() - born.getFullYear();
      else
        return now.getFullYear() - born.getFullYear() - 1;
    }

document.getElementById("dateInput").addEventListener("change", function() {
    var input = this.value;
    var dateEntered = new Date(input);
    
       var now = new Date();
        var birthdate = input.split("-");
        var born = new Date(birthdate[0], birthdate[1]-1, birthdate[2]);
        age=get_age(born,now);
     
        console.log(birthdate[2]+" : "+birthdate[1]+" : "+birthdate[0]);
        console.log(age);
    
        if (age<=18)
        {
       alert("Input Error - Age should be greater then or equal to 18");
            return false;
        }
});
Birthday: <input type="date" id="dateInput" name="bday">

also read for more info

Junius L
  • 15,881
  • 6
  • 52
  • 96