zend framework 2 - compare 2 inputs using validato

2019-07-19 22:26发布

问题:

I'm new to zend framework 2 and I have a question on comparing two inputs in the factory-backed form. My scenario is like following:

I want to compare two inputs, for example, $startDate and $endDate. I want to validate that $startDate is always less than $endDate. How I'm going to do this? For example:

$inputFilter->add($factory->createInput(array(
                'name'     => 'startDate',
                'required' => true,
                'validators' => array(
                    array(
                        'name'    => 'LessThan',
                        'options' => array(
                            'max'      => $endDate,
                        ),
                    ),
                ),
            )));

FYI, I'm following the Album tutorial and the $inputFilter is created in the classTable.php.

Thanks

回答1:

Thanks to Crisp! I solved it with something similar:

$inputFilter->add($factory->createInput(array(
            'name'     => 'startDate',
            'required' => true,
            'name'     => 'Callback',
                'options' => array(
                    'message' => array( 
                        Callback::INVALID_VALUE => 'Invalid period is given.',
                    ),
                    'callback' => function($value, $context=array()) {
                        return $value < $context['endDate'];
                    },
                ),
            )));


回答2:

The above answer probably be correct, but there might be some syntax or Callback error might be occur. The reason is, We generally use Callback Validation function in Models InputFilters, Not in a forms definition section(as of Zend Framework version 2.2.1).

This call back script part should come inside Model - InputFilters, Please refer this link: https://stackoverflow.com/a/19263037/2190889

As per this Url reference, date validation part works perfectly.