Jump to content
Sign in to follow this  
Battousai

[PHP] Validar datas

Recommended Posts

Battousai

Já que parece não haver um snippet deste género e as outras soluções serem aparentemente mais verbosas e complexas, deixo aqui uma alternativa.

Este função usa a flexibilidade e simplicidade das funções preg_match e checkdate (cliquem nas funções para lerem o manual).

Neste caso validamos a data no formato AAAA-mm-dd, mas podem facilmente alterá-la ou adicionar uma camada lógica de forma a satisfazer as vossas necessidades.

class valid {
   /**
    * Permite validar datas de formato YYYY-MM-DD
    *
    * @param string $str string de data a validar
    * @return bool
    */
   public static function standard_date($str)
   {
       return preg_match("~^(\d{4})-(\d{1,2})-(\d{1,2})$~", $str, $matches) AND
	checkdate($matches[2], $matches[3], $matches[1]);
   }
}

// Uso:
valid::standard_date('2000-04-13'); // true
valid::standard_date('2000-5-20'); // true
valid::standard_date('2000-2-30'); // false

  • Vote 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.