Validate date of birth so that you can not register under 18 (JavaScript)

-1

I have a field called 'txtdata_nasc' of type date. I need the user not to enter a date that makes him less than 18 years old, but also that he can not have an absurd age, such as 100 years old, I need him to enter at most a date of birth that makes him 60 years old. For example, it can not type (using today's example 05/05/2018) a date greater than '05 / 05/2000 'and a date less than 05/05/1958.

    
asked by anonymous 05.05.2018 / 07:12

1 answer

1

A simple solution to validate if the person is about 18 years old is to create a date with the same month and day, and with the year added to 18. Then you just need to compare if that date is less than or greater than current date.

Example:

const inputNasc = document.getElementById("txtdata_nasc");

document.querySelector("form").addEventListener("submit", function(){
  //obter array com [ano,mes,dia] através de split("-") e convertendo em numero com Map
  let nasc = inputNasc.value.split("-").map(Number);
  //construir data 18 anos a seguir a data dada pelo usuario
  let depois18Anos = new Date(nasc[0] + 18, nasc[1] - 1, nasc[2]);
  let agora = new Date();
  
  if (depois18Anos <= agora){
    console.log("Maior de 18");
  }
  else {
    console.log("Menor de 18");
  }
  event.preventDefault(); //só para não mudar de pagina na submissão do formulario
});
<form>
  <input type="date" id="txtdata_nasc">
  <input type="submit" value="Validar">
</form>

It is important to note that since the months in Javascript start at zero, the month part has to be subtracted from 1 with nasc[1] - 1 .

To validate for less than 100 years you can use exactly the same principle, changing only in comparison:

let nasc = inputNasc.value.split("-").map(Number);
let depois18Anos = new Date(nasc[0] + 18, nasc[1] - 1, nasc[2]);
let depois100Anos = new Date(nasc[0] + 100, nasc[1] - 1, nasc[2]);
let agora = new Date();

if (depois18Anos > agora){
  console.log("Menor de 18");
}
else if(depois100Anos < agora){
  console.log("Maior de 100");
}
else {
  console.log("valido");
}

With destructuring assignment can make construction simpler and clearer of the dates X years ahead:

let [ano, mes, dia] = inputNasc.value.split("-").map(Number);
//    ^----^----^--- Destructuring assignment
let depois18Anos = new Date(ano + 18, mes - 1, dia);
let depois100Anos = new Date(ano + 100, mes - 1, dia);
    
05.05.2018 / 12:24