Tuesday, September 25, 2007

Try Zend Framework vol.4 "Validate Date"

As you know, Zend Framework has a lot of fancy validators like Zend_Validte_Ccnum.
But, it comes to "Zend_Validate_Date", I have to be quiet, because it only allows "YYYY-mm-dd" format.
Date sometimes look like "YYYY/mm/dd" but the validator returns "false". :<

It's Okay. But it should be more flexible, isn't it?

Zend Framework has Date class which is pretty powerful to create date object, but it's also powerful as Date validator.
So I wrote a Date validator.

library/Hoge/Validate/Date.php
<php
require_once 'Zend/Validate/Abstract.php';
require_once 'Zend/Date.php';

class Hoge_Validate_Date extends Zend_Validate_Abstract
{

/**
* Invalid date error message.
*/
const INVALID = 'dateInvalid';

/**
* Validation failure message template.
*
* @var array
*/
protected $_messageTemplates = array(
self::INVALID => "'%value%' does not appear to be a valid date"
);

/**
* Defined by Zend_Validate_Interface
*
* Return if the date is correct.
*
* @param string $value
* @return boolean
*/
public function isValid($value)
{

$valueString = (string) $value;

$this->_setValue($valueString);

if (!Zend_Date::isDate($value)) {
$this->_error(self::INVALID);
return false;
}

return true;
}

}


To use it
application/controller/HogeController.php
<php
function dateValidateAction()
{
$date = '2004/02/29';

require 'Hoge/Validate/Date.php';
$validator = new Hoge_Validate_Date();
echo $validator->isValid($date);
exit;
}

Return "true".
It distinguish "/" and validate the Date correctly!! :p

(weight 86.4kg BMI 29%)

Labels:

0 Comments:

Post a Comment

<< Home