Validating multiple optional form fields with Zend Framework

ぃ、小莉子 提交于 2019-12-05 17:28:21

If I understand you right, you want your form elements to not be required, but prevent them to be empty (except if one of them is not empty) using a custom validator? Then, in order to not skip the validation chain, you need to prevent them to be empty calling the method setAllowEmpty(false) in each of your elements.

Finally, in your custom validator, you will have something like this:

foreach ($this->_listOfFields as $field) {
    if (isset($context[$field]) AND $context[$field])
    {
        return true;
    }
}

Also, make sure your elements are not required (setRequired(false)).

The problem is that if any field is filled, the multi_checkbox element doesn't exists in the form, and then it won't be validated.

One solution is the follow: Use a hidden option always checked and validate that this always is checked this more one of the others.

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