Home > database >  How to validate age in javascript with input date type
How to validate age in javascript with input date type

Time:12-20

So I made an input type="date" but was unable to validate if the user entered a valid (18 yrs old). How can I make it validate?

Sample code:

HTML:

<label>
            Birthdate:
            <br /><input
              type="date"
              id="birthdate"
              placeholder="Enter birthdate"
            /><br />
            <span  id="bday"></span>
          </label>

JS:

var birth = document.getElementById('birthdate').value;
  if (birth == '') {
    document.getElementById('bday').innerHTML = 'Please enter birthdate.';
  }

I can only validate if there is no user input. I want it to store an error in notif if the age is under 18 years old.

CodePudding user response:

You can use the min/max attribute of the date input that is natively provided by HTML5. Check out this link for more information on the same - https://www.w3schools.com/tags/att_input_min.asp

CodePudding user response:

you can check differnce between their birthday date and today's date :

var their_date = new Date(2010, 6, 17);
var today = new Date();
var date2 = new Date(today.getFullYear(),today.getMonth() 1,today.getDate());
var diff = new Date(date2.getTime() - their_date.getTime());
console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
  • Related