How to validate date of birth between the year 1900 and Today?

Asked

Viewed 3,011 times

3

Validating date of birth with 3 fields?

I have the field "data1" with the day, "data2" with the month and "data3" with the year, I need to validate the date of birth. These 3 fields come from a comic.

It would be something like that:

if (validaDataDeNascimento($data1/$data2/$data3))
{
   echo "Data de nascimento inválida.";
}
  • 1900 to present date

  • What do you mean by "pulling from the bd"? Do you have invalid data in the database and want to validate by php? Or do you want to validate before arriving at the database?

1 answer

7


I called your variables $dia, $mes and $ano for easy reading.

If you want to know if the date is valid, just use the checkdate:

checkdate( $mes, $dia, $ano ) // Atenção à ordem dos parâmetros.

To see if the date is today or earlier:

if ( mktime( 0, 0, 0, $mes, $dia, $ano ) < time() ) // não precisa de <= (a hora é 0, 0, 0)

To see if the year is greater than or equal to 1900:

if ( $ano >= 1900 )

Putting it all together and reversing the checks:

if ( !checkdate( $mes , $dia , $ano )                   // se a data for inválida
     || $ano < 1900                                     // ou o ano menor que 1900
     || mktime( 0, 0, 0, $mes, $dia, $ano ) > time() )  // ou a data passar de hoje
{
   echo 'Data inválida';
}

If it makes a difference the "turn" of the date at midnight:

The functions used above are based on the server time. If you need more accuracy, an alternative is to use the class DateTime, which accepts comparisons from the PHP 5.2.2, and in addition to date_default_timezone_set, Timezone can be set individually in each of the DateTimes, so as not to interfere with other parts of the script.

date_default_timezone_set('America/Sao_Paulo');
$hoje = new DateTime('NOW');
$nascimento = new DateTime();
$nascimento->setDate( $ano, $mes, $dia ); // Novamente, atenção à ordem dos parâmetros.

if ( $nascimento > $hoje ) || ... etc ...
  • thank you!!!!!!!!!!!!!!

Browser other questions tagged

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