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

3

How to validate birth date with 3 fields?

I have the field "date1" with the day, "date2" with the month and "date3" with the year, I need to validate the date of birth. These 3 fields come from a bd .

It would look something like this:

if (validaDataDeNascimento($data1/$data2/$data3))
{
   echo "Data de nascimento inválida.";
}
    
asked by anonymous 02.05.2014 / 05:39

1 answer

7
  

I called your variables from $dia , $mes and $ano to make reading easier.

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

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

To see if the date is today or before:

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 everything 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 you make a difference to the "date" of the date at midnight:

The functions used above are based on server time. If you need more precision, an alternative is to use the DateTime class, which accepts comparisons from PHP 5.2.2, and in addition to date_default_timezone_set , timezone can be set individually in each of DateTime s, 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 ...
    
02.05.2014 / 05:44