在 zendframework2 中验证日期 [英] validating date in zendframework2
本文介绍了在 zendframework2 中验证日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 zf2 验证日期字段形式.我设置了格式"选项以获得我需要的格式.但是每次我验证它时都会出错.验证器看起来像这样:
Hiho, I would like to validate a date field from an zf2 form. I set the 'format' option to get the format I need. But at every time I validate it i get an error. The validator looks like this:
$inputFilter->add($factory->createInput(array(
'name' => 'user_data_birth',
'required' => false,
'validators' => array(
array(
'name' => 'Date',
'options' => array(
'format' => 'd.m.Y',
'locale' => 'de',
'messages' => array(
\Zend\Validator\Date::INVALID => 'Das scheint kein gültiges Datum zu sein.',
\Zend\Validator\Date::INVALID_DATE => 'Das scheint kein gültiges Datum zu sein. (Invalid Date)',
\Zend\Validator\Date::FALSEFORMAT => 'Das Datum ist nicht im richtigen Format.',
),
),
),
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => 'Bitte geben Sie das Datum an'
),
),
)
),
)));
但每次我都会收到日期格式错误的错误信息.
But I get every time an error that the date is in the wrong format.
推荐答案
可以解决开始日期应该小于结束日期验证的问题,使用回调函数如下:
You can solve the problem of, start date should be less than end date validation, using the Callback function as below:
$inputFilter->add($factory->createInput(array(
'name' => 'end_date',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'The end date should be greater than start date',
),
'callback' => function($value, $context = array()) {
$startDate = \DateTime::createFromFormat('d-m-Y', $context['start_date']);
$endDate = \DateTime::createFromFormat('d-m-Y', $value);
return $endDate >= $startDate;
},
),
),
),
)));
使用上面的代码,我已经解决了我的问题.我希望这会有所帮助.
Using the above code, I have solved my problem. I hope this helps.
这篇关于在 zendframework2 中验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文