I have two Zend\Form\Element\Dateselect
elements in my form and I'm trying to validate that dateEnd > dateBeg
.
These are the values in my form:
$startDate = new DateSelect('dateBeg');
$startDate->setLabel('Start Date');
$startDate->setMinYear(2016);
$startDate->setMaxYear(date("Y"));
$startDate->setDayAttributes(array(
'name' => 'dayBeg',
));
$startDate->setMonthAttributes(array(
'name' => 'monthBeg',
));
$startDate->setYearAttributes(array(
'name'=> 'yearBeg',
));
$this->add($startDate);
$endDate = new DateSelect('dateEnd');
$endDate->setLabel('End Date');
$endDate->setMinYear(2016);
$endDate->setMaxYear(date("Y"));
$endDate->setDayAttributes(array(
'name' => 'dayEnd',
));
$endDate->setMonthAttributes(array(
'name' => 'monthEnd',
));
$endDate->setYearAttributes(array(
'name'=> 'yearEnd',
));
$this->add($endDate);
I saw this solution for comparing two Date
elements: zend framework 2 - compare 2 inputs using validator?
I tried to use this in my validation file, but the validation of dateEnd
seems to only be affected by the 'required' filter and not my custom validator.
$inputFilter->add($factory->createInput(array(
'name' => 'dateEnd',
'required' => false,
'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('Y-m-d', $context['dateBeg']);
$endDate = \DateTime::createFromFormat('Y-m-d', $value);
return $endDate > $startDate;
},
),
),
),
)));
I modified my form to use Date
instead of DateSelect
and this validation seems to work as intended, but I would prefer to use the DateSelect
element. My guess is that there is something wrong with the Callback
function / validator because I've used debug messages in there, but they don't get called. Is there a reason this validator isn't being called on my form?