3

如何在 Zend Framework (Zend_Filter_Input) 中验证多维数组?

例子:

  • 输入必须是数组
  • 输入必须具有“角色”和“名称”
  • “角色”必须是数组
  • “角色”中的所有元素都必须是数组
  • 'roles' 中的所有元素必须有 'name' 和 'id','access' 是可选的
  • 'id' 必须是 int
  • “访问”必须是数组

$input = array(
    'roles' => array(
        array('name' => 'Test', 'id' => 1),
        array('name' => 'Test2', 'id' => 2, 'access' => array('read', 'write'))
    ),
    'name' => 'blabla'
);
4

1 回答 1

1

前几天有一个类似的问题:Passing an array as a value to Zend_Filter

简而言之,如果您使用Zend_Filter_Input,它会将数组值单独传递给关联的验证器。因此,不能将数组作为一个整体使用,而可以使用各个组件。

编辑:一个可能的解决方案是创建您自己的特定Zend_Validate类并在isValid方法中包含所有检查,如下所示:

class MyValidator extends Zend_Validate_Abstract
{
    const MESSAGE = 'message';

    protected $_messageTemplates = array(
        self::MESSAGE => "Invalid format for the array"
    );

    public function isValid($value)
    {
        if (!is_array($value)) {
            $this->_error();
            return false;
        }

        // ...

        return true;
    }
}

希望有帮助,

于 2011-11-29T09:11:37.340 回答