Conditionally required in Zend Framework's 2 InputFilter

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I am making an application using Zend Framework 2. I am validating input using it's InputFilter. Is it possible, to make some Inputs 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?

回答1:

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:

$filter = new \Zend\InputFilter\InputFilter(); $type   = new \Zend\InputFilter\Input('type'); $smth   = new \Zend\InputFilter\Input('smth');  $smth     ->getValidatorChain()     ->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))     ->attach(new \Zend\Validator\Callback(function ($value) use ($type) {         return $value || (1 != $type->getValue());     }));  $filter->add($type); $filter->add($smth); 

This will basically work when the value smth is an empty string and the value for type is not 1. If the value for type is 1, then smth has to be different from an empty string.



回答2:

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:

$filter = new \Zend\InputFilter\InputFilter(); $type   = new \Zend\InputFilter\Input('type'); $smth   = new \Zend\InputFilter\Input('smth');  $smth     ->getValidatorChain()     ->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))     ->attach(new \Zend\Validator\Callback(function ($value, $context){         return $value || (1 != $context['type']);     }));  $filter->add($type); $filter->add($smth); 


回答3:

Unfortunately you'd have to set the required option based on your conditions like so:

$filter->add($factory->createInput(array(     'name' => 'smth',     'required' => (isset($_POST['type']) && $_POST['type'] == '1'), ))); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!