1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48:
<?php
namespace Coast\Validator\Rule;
use Coast\Validator\Rule;
class DateTime extends Rule
{
protected $_format;
public function __construct($format = null)
{
$this->format($format);
}
public function format($format = null)
{
if (func_num_args() > 0) {
$this->_format = $format;
return $this;
}
return $this->_format;
}
protected function _validate($value)
{
if (!is_scalar($value)) {
$this->error();
return;
}
if (isset($this->_format)) {
$date = \DateTime::createFromFormat($this->_format, $value);
if ($date === false) {
$this->error();
}
} else {
try {
$date = new \DateTime($value);
} catch (\Exception $e) {
$this->error();
}
}
}
}