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:
-
$validator = new Zsamer_Validate_DateTime('YYYY-MM-dd HH:mm:ss', 'es_CL');
-
$fecha = "2008-10-18 10:34:00";
-
-
if ($validator->isValid($fecha)) {
-
// Fecha es valida
-
} else {
-
// Fecha es invalida; imprime mensajes de error
-
foreach ($validator->getMessages() as $messageId => $message) {
-
echo "Error en la validación '$messageId': $message\n";
-
}
-
}
La clase validadora:
PHP:
-
<?php
-
require_once 'Zend/Validate/Abstract.php';
-
-
class Zsamer_Validate_DateTime extends Zend_Validate_Abstract
-
{
-
/**
-
* Format for parsing the date string
-
*
-
* @var string
-
*/
-
protected $_format;
-
-
/**
-
* Locale for parsing date parts.
-
*
-
* @var string
-
*/
-
protected $_locale;
-
-
/**
-
* Validation failure message key for when the value does not follow the YYYY-MM-dd HH:mm:ss format
-
*/
-
const NOT_YYYY_MM_dd_HH_mm_ss = 'dateNotYYYY_MM_dd_HH_mm_ss';
-
-
/**
-
* Validation failure message key for when the value does not appear to be a valid date
-
*/
-
const INVALID = 'dateInvalid';
-
-
/**
-
* Validation failure message template definitions
-
*
-
* @var array
-
*/
-
self::NOT_YYYY_MM_dd_HH_mm_ss => "'%value%' is not of the format YYYY-MM-dd HH:mm:ss",
-
self::INVALID => "'%value%' does not appear to be a valid date"
-
);
-
-
public function __construct($format, $locale)
-
{
-
$this->_format = $format;
-
$this->_locale = $locale;
-
}
-
-
/**
-
* Defined by Zend_Validate_Interface
-
*
-
* Returns true if and only if $value is a valid date of the format YYYY-MM-dd HH:mm:ss
-
*
-
* @param string $value
-
* @return boolean
-
*/
-
public function isValid($value)
-
{
-
$valueString = (string) $value;
-
-
$this->_setValue($valueString);
-
-
if (!Zend_Date::isDate($valueString, $this->_format, $this->_locale)) {
-
$this->_error(self::NOT_YYYY_MM_dd_HH_mm_ss);
-
return false;
-
}
-
-
return true;
-
}
-
-
}
Hasta la próxima ![]()
Comentarios
One Response to “Validar Fechas”
Deja tu comentario

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.