简体   繁体   中英

Zend Validators and multidimensional array

How do i validate multidimensional array in Zend Framework (Zend_Filter_Input)?

Example:

  • Input must be array
  • Input must have 'roles' and 'name'
  • 'roles' must be array
  • All element in 'roles' must be array
  • All element in 'roles' must have 'name' and 'id', 'access' is optional
  • 'id' must be int
  • 'access' must be array

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

There was a similar question some days ago: Passing an array as a value to Zend_Filter

In short, if you use Zend_Filter_Input , it will pass the array values individually to the associated validators. So, it's not possible to use the array as a whole, but the individual components.

EDIT : A possible solution would be to create your own specific Zend_Validate class and include all the checks in the isValid method, something like the following:

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;
    }
}

Hope that helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM