Validar Fechas

Por zsamer en Octubre 18, 2008

Hoy vamos a ver un tema bien corto y sencillo, se trata de validar fechas con Zend_Validate.

Una simple clase que hereda de Zend_Validate_Abstract y utiliza Zend_Date para verificar si la fecha es o no válida.

Un ejemplo de uso:

PHP:
  1. $validator = new Zsamer_Validate_DateTime('YYYY-MM-dd HH:mm:ss', 'es_CL');
  2. $fecha = "2008-10-18 10:34:00";
  3.  
  4. if ($validator->isValid($fecha)) {
  5.     // Fecha es valida
  6. } else {
  7.     // Fecha es invalida; imprime mensajes de error
  8.     foreach ($validator->getMessages() as $messageId => $message) {
  9.         echo "Error en la validación '$messageId': $message\n";
  10.     }
  11. }


La clase validadora:

PHP:
  1. <?php
  2. require_once 'Zend/Validate/Abstract.php';
  3.  
  4. class Zsamer_Validate_DateTime extends Zend_Validate_Abstract
  5. {
  6.     /**
  7.      * Format for parsing the date string
  8.      *
  9.      * @var string
  10.      */
  11.     protected $_format;
  12.  
  13.     /**
  14.      * Locale for parsing date parts.
  15.      *
  16.      * @var string
  17.      */
  18.     protected $_locale;
  19.  
  20.     /**
  21.      * Validation failure message key for when the value does not follow the YYYY-MM-dd HH:mm:ss format
  22.      */
  23.     const NOT_YYYY_MM_dd_HH_mm_ss = 'dateNotYYYY_MM_dd_HH_mm_ss';
  24.  
  25.     /**
  26.      * Validation failure message key for when the value does not appear to be a valid date
  27.      */
  28.     const INVALID        = 'dateInvalid';
  29.  
  30.     /**
  31.      * Validation failure message template definitions
  32.      *
  33.      * @var array
  34.      */
  35.     protected $_messageTemplates = array(
  36.     self::NOT_YYYY_MM_dd_HH_mm_ss => "'%value%' is not of the format YYYY-MM-dd HH:mm:ss",
  37.     self::INVALID        => "'%value%' does not appear to be a valid date"
  38.     );
  39.  
  40.     public function __construct($format, $locale)
  41.     {
  42.         $this->_format = $format;
  43.         $this->_locale = $locale;
  44.     }
  45.  
  46.     /**
  47.      * Defined by Zend_Validate_Interface
  48.      *
  49.      * Returns true if and only if $value is a valid date of the format YYYY-MM-dd HH:mm:ss
  50.      *
  51.      * @param  string $value
  52.      * @return boolean
  53.      */
  54.     public function isValid($value)
  55.     {
  56.         $valueString = (string) $value;
  57.  
  58.         $this->_setValue($valueString);
  59.  
  60.         if (!Zend_Date::isDate($valueString, $this->_format, $this->_locale)) {
  61.             $this->_error(self::NOT_YYYY_MM_dd_HH_mm_ss);
  62.             return false;
  63.         }
  64.  
  65.         return true;
  66.     }
  67.  
  68. }

Hasta la próxima :-)

Comentarios

One Response to “Validar Fechas”

  1. viz on Enero 22nd, 2010 2:13 pm

    Hola,

    No entiendo del todo como funciona Zend_Date::isDate($valueString, $this->_format, $this->_locale)

    El ejemplo devuelve válido pasándole ( por ejemplo ) cualquiera de estos formatos:

    YYYY-MM-dd HH
    YYYY-MM-dd
    YYYY
    Y
    etc…

    Por que, si la fecha siempre es la misma ?

    PD. Gran blog.

Deja tu comentario




XHTML: puedes usar estas etiquetas: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>