I am making an application using Zend Framework 2. I am validating input using it's InputFilter
. Is it possible, to make some Input
s required conditionally? I mean I have code like that:
$filter = new \Zend\InputFilter\InputFilter();
$factory = new \Zend\InputFilter\Factory();
$filter->add($factory->createInput(array(
'name' => 'type',
'required' => true
)));
$filter->add($factory->createInput(array(
'name' => 'smth',
'required' => true
)));
I want the field something
, to be required, ONLY when type
is equal 1
. Is there a built-in way to do that? Or should I just create custom validator?
You can also use
setValidationGroup
for this.Create your own
InputFilter
class where you set validation groups depending on the data that is set inside the inputfilter before executing the actual validation.This is just a simple example to show what is possible with
setValidatioGroup
, you can create your own combinations for setting validation groups after your specific needs.I couldn't quite get the example by Ocramius to work, as $type->getValue was always NULL. I changed the code slightly to use $context and this did the trick for me:
Unfortunately you'd have to set the required option based on your conditions like so:
First of all, you may want to enable validation on empty/null values as of Empty values passed to Zend framework 2 validators
You can use a callback input filter as in following example:
This will basically work when the value
smth
is an empty string and the value fortype
is not1
. If the value fortype
is1
, thensmth
has to be different from an empty string.