How to check if a value is a date

7

How can I check if a post is of type date ?

There has been a situation where I have a form that contains a date field:

<form action="" method="post">
    <input type="date" name="data">
    <input type="submit" name="enviar" value="enviar"/>
</form>

I need to make sure the sending of $_POST['data'] is a valid date.

One problem that has happened is that mozilla firefox leaves a field open to the user typing. In google chrome and in edge I no longer have this problem.

Another problem is if the user is in the element inspector and change the input type date to text . If it sends the form with some incorrect value (eg single quote, letters) it will give error at the time of the query.

My intention is to validate the date after it is submitted by the form . How can I do this?

NOTE: I'm using php

    
asked by anonymous 19.10.2016 / 18:20

3 answers

5

With this check it is possible:

$data = DateTime::createFromFormat('d/m/Y', $_POST['data']);
if($data && $data->format('d/m/Y') === $_POST['data']){
   echo 'é data';
}
    
19.10.2016 / 18:30
3

You can use the DateTime class to convert the value to an object, format it, and finally convert it, from there compare the original value ( $data ) with the value of the object, invalid or out of the specified format are passed.

//data valida 
//$data = '19/10/2016';

//data invalida
$data = '30/02/2016';
$d = DateTime::createFromFormat('d/m/Y', $data);
if($d && $d->format('d/m/Y') == $data){
    echo 'data valida';
}else{
    echo 'data invalida';
}
    
19.10.2016 / 18:31
3

It can also be done like this:

<?php
//pega a data
$data = "03/04/2012";

//cria um array
$array = explode('/', $data);

//garante que o array possue tres elementos (dia, mes e ano)
if(count($array) == 3){
    $dia = (int)$array[0];
    $mes = (int)$array[1];
    $ano = (int)$array[2];

    //testa se a data é válida
    if(checkdate($mes, $dia, $ano)){
        echo "Data '$data' é válida";
    }else{
        echo "Data '$data' é inválida";
    }
}else{
    echo "Formato da data '$data' inválido";
}
?>

Hope it helps.

    
19.10.2016 / 18:41