How to check if a value is date

Asked

Viewed 6,551 times

8

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

There was 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 check if sending the $_POST['data'] is a valid date.

One problem that happened is that Mozilla firefox leaves an open field for the user to type. In google Chrome and edge I no longer have this problem.

Another problem is if the user goes to the element inspecter and changes the input type date for text. If it sends the form with some incorrect value (e.g. single quote, letters) will give error at the time of the query.

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

OBS.: I’m using php

3 answers

7


With this check is possible:

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

    Your solution worked out!

3

You can use the class DateTime to convert the value into an object, format it and finally convert it, from there compare the original value ($data) with the object value, this ensures that invalid or out of specified formatted date is passed forward.

//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';
}
  • Valeu rray, helped a lot bro!

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";
}
?>

I hope it helps.

  • 2

    I particularly like the checkdate! +1

  • thanks buddy!

Browser other questions tagged

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