validating date in zendframework2
validation, zend-framework2
Solution
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.
Problem
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.