Display an error in case a user inputs an invalid formatted datetime string

resolves 
This commit is contained in:
Johannes Meyer 2015-02-12 09:04:50 +01:00
parent a630db93e8
commit a2f3e7d4f7
1 changed files with 18 additions and 2 deletions
library/Icinga/Web/Form/Validator

View File

@ -5,6 +5,7 @@ namespace Icinga\Web\Form\Validator;
use DateTime; use DateTime;
use Zend_Validate_Abstract; use Zend_Validate_Abstract;
use Icinga\Util\DateTimeFactory;
/** /**
* Validator for date-and-time input controls * Validator for date-and-time input controls
@ -13,6 +14,21 @@ use Zend_Validate_Abstract;
*/ */
class DateTimeValidator extends Zend_Validate_Abstract class DateTimeValidator extends Zend_Validate_Abstract
{ {
const INVALID_DATETIME_TYPE = 'invalidDateTimeType';
const INVALID_DATETIME_FORMAT = 'invalidDateTimeFormat';
/**
* The messages to write on differen error states
*
* @var array
*
* @see Zend_Validate_Abstract::$_messageTemplates
*/
protected $_messageTemplates = array(
self::INVALID_DATETIME_TYPE => 'Invalid type given. Instance of DateTime or date/time string expected',
self::INVALID_DATETIME_FORMAT => 'Date/time string not in the expected format: %value%'
);
protected $local; protected $local;
/** /**
@ -38,14 +54,14 @@ class DateTimeValidator extends Zend_Validate_Abstract
public function isValid($value, $context = null) public function isValid($value, $context = null)
{ {
if (! $value instanceof DateTime && ! is_string($value)) { if (! $value instanceof DateTime && ! is_string($value)) {
$this->_error(t('Invalid type given. Instance of DateTime or date/time string expected')); $this->_error(self::INVALID_DATETIME_TYPE);
return false; return false;
} }
if (is_string($value)) { if (is_string($value)) {
$format = $this->local === true ? 'Y-m-d\TH:i:s' : DateTime::RFC3339; $format = $this->local === true ? 'Y-m-d\TH:i:s' : DateTime::RFC3339;
$dateTime = DateTime::createFromFormat($format, $value); $dateTime = DateTime::createFromFormat($format, $value);
if ($dateTime === false || $dateTime->format($format) !== $value) { if ($dateTime === false || $dateTime->format($format) !== $value) {
$this->_error(sprintf(t('Date/time string not in the expected format %s'), $format)); $this->_error(self::INVALID_DATETIME_FORMAT, DateTimeFactory::create()->format($format));
return false; return false;
} }
} }