Validating Date of birth

Asked

Viewed 4,978 times

2

Hello, I am trying to validate birth date less than 15 years using the following rule:

1- If the user enters the date of birth, check if the day, month and year the user has typed, corresponds to less than 15 years, if yes, the button will be hidden.

Insert the following function below:

function calculaIdade(dobString) {

var data_nasc = document.getElementById('data_cri').value.split("/");
var verifica = data_nasc[2]+data_nasc[1]+data_nasc[0];

var dob = new Date(dobString);
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
var verifica = currentYear - dob.getFullYear();

alert(verifica); //mostra a idade
alert(currentYear); // mostra o ano

alert(birthdayThisYear);

if (verifica >= 15 && currentYear < birthdayThisYear ){
    //alert('pode');
    document.getElementById('mostravid').style.display = "block";
} else {
    //alert('nao pode');
    document.getElementById('mostravid').style.display = "none";

}

if (verifica == ''){
    document.getElementById('mostravid').style.display = "none";

  }
}

<input type='text' name='data_cri' id='data_cri' value='<?=$data_cri?>' size='12' maxlength='10' onkeyup='formataData(this,this.value);' onblur='return calculaIdade(this.value)'>

For now it is working validating only per year, I would like it to validate as follows:

the user was born 21/09/2000 however, his age is 14 years using this function above, tomorrow is day 22/09, the user will enter the data 22/09, the function will calculate 15 years, ok .

I would like help from you to calculate this way.

Thank you

  • We have a calculation problem when we consider the leap year... if making a difference by the exact time spent the day before the birthday can be considered as ok..

  • have some example there ?

  • 1

    If so, please expedite your work :http://bit.ly/1efORk3 or http://bit.ly/1KqRCR8 this framework.

  • Thanks for the link and the tips ...

4 answers

2

a solution counting the milliseconds

//define as duas datas base...
var actualDate = new Date();
//validando 25/09/2000 que ainda nao completou 15 anos
var birthDate = new Date("2000", "8", "25", "0", "0", "0");

// pega o milisegundo de cada uma
var actualMili = actualDate.getTime();
var selectMili = birthDate.getTime();

// 15 anos em milisegundos
var timeToTest= 1000 * 60 * 60 * 24 * 365 * 15; //15 anos em mili segundos...

//faz a diferença entre as datas e o tempo calculado
if( ( actualMili -  selectMili) >= timeToTest){
  document.body.textContent = "Pessoa com mais de 15 anos";
}
else{
  document.body.textContent = "Pessoa com menos de 15 anos";
}

  • It did not work h3nr1ke, any date I enter shows that the Person over 15 years ...

  • Opa... as you are entering the dates, remembering that the month should be placed as number 0 to 11, if you run the code as is and put the year 2001 for example, You have to show less than 15 years... remembering the leap year bid that still remains in this example...

  • @hulckb put the test here take a look

  • @h3nr1ke, I moved your example to the body of your question.

  • show @Tobymosque, really just complicated separating, thank you.

2


Guys, it worked out ... I had to use ajax and php for security reasons, follow the script for anyone who wants to reuse.

 //Data de nascimento
$data_cri = date('Y-m-d',strtotime(str_replace('/','-',$_POST['data_cri'])));   

// data atual
$dt_fim = date('Y-m-d'); 

if (date('Y') - substr($data_cri,0,4) < 15){
        $date = str_replace('-', '/', $data_cri);
        echo "<div><h4>Data ".date('d/m/Y', strtotime($date))." fora do intervalo. <br> Menor que 15 anos não pode ser cadastrado!<h4> </div>"; 

}

// diferenca entre duas datas
if( isset($data_cri) && $data_cri!="" && isset($dt_fim) && $dt_fim!="") {
    $data_cri = DateTime::createFromFormat('Y-m-d', $data_cri);
    $dt_fim = DateTime::createFromFormat('Y-m-d', $dt_fim);

    if ((int)$dt_fim->diff($data_cri)->format('%y') >=15){
        echo "<div align='center'><input type='submit' value='Prosseguir'></div>";
        echo "<div align='center'><h3>Idade: ".(int)$dt_fim->diff($data_cri)->format('%y').' anos<h3></div>';
    }
} 
  • Ajax to calculate date with values that are already on the screen? What security issues?

  • I was hiding a div when the age was less than 15, so if the malicious user inspected the element, he himself could change the property to display='block' in which case the button would be enabled and he could proceed, so I created the call ajax, abs

  • Dude, never just delegate validations to the user interface. I suppose a validation in the button action would be less complex and less costly to navigation and the system than making additional requests to the server. You can also remove the element via Javascript, avoiding the possibility of displaying the button in invalid cases. And what happens if the user tries to submit the data with Javascript disabled or via a batch?

1

you can simply add 15 years to current date.

var formulario = document.getElementById("formulario");
var nascimento = document.getElementById("nascimento");
var enviar = document.getElementById("enviar");

var mensagemErro = function (event, input, mensagem) {
  //input.setCustomValidity(mensagem);
  alert(mensagem);
  event.preventDefault();
}

formulario.addEventListener("submit", function (event) {
  var data = nascimento.value;
  //nenhuma data informada
  if (!data) {
    return mensagemErro(event, nascimento, "Campo nascimento não informado");
  }

  //O browser não realizou a conversão de forma nativa
  if (!(data instanceof Date)) {
    data = data.split('/').reverse().join('-');
    data = Date.parse(data);
    if (!isNaN(data)) {
      data = new Date(data);
    }
  }

  //a data informada não é valida
  if (!data) {
    return mensagemErro(event, nascimento, "Campo nascimento não é valido");
  }

  var atual = new Date();
  data.setFullYear(data.getFullYear() + 15);  

  //menor de 15 anos.
  if (data > atual) {
    return mensagemErro(event, nascimento, "Nascimento posterior a 15 anos atrás");
  }
})
<form id="formulario">
  <input id="nascimento" type="date" />
  <input id="enviar" type="submit" value="Enviar" />
</form>

In the above case, I am using a date input, so I only need to convert the date manually if the value property does not return me a date.

  • this script did not run Tobymosque ...,

  • 1

    @hulckb, was getting lost in the display of messages, I put an alert.

  • as it would be in the case of the entry of the year dd/mm/yyyy ?

  • 1

    the script already treats this behavior, for example if you open in an example in a browser that does not have the input:date implemented (eg: Firefox), you will be able to enter a date in the format dd/MM/yyyy, in this case he will enter the condition !(data instanceof Date) and the algotimo data.split('/').reverse().join('-') will convert dd/MM/yyyy in yyyy-MM-dd which is a valid date in the format ISO 8601

1

Create a date object with the user’s date of birth and another date with the current date less 15 years. If the user’s date of birth is less than the current date less than 15 years the user is less than 15 years old.

function idadeMaiorQue(dataNascimento, idadeMinima) {
    var userDob = new Date(dataNascimento);
    var maxDob = new Date();

    maxDob.setFullYear(maxDob.getFullYear() - idadeMinima);

    return !(userDob < maxDob);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.