zerkms
zerkms

Reputation: 255015

How to validate if value is an array using Zend_Filter_Input?

Zend performs validation for Zend_Filter_Input recursively, so the code:

    $data = array(
        'update' => array(1, 2, 3)
    );

    $validators = array(
        'update' => array(
            new Zend_Validate_Callback('is_array'),
            'presence' => 'required'
        )
    );

    $filter = new Zend_Filter_Input(array(), $validators, $data);
    var_dump($filter->isValid());
    var_dump($filter->getMessages());

returns false and messages that 1, 2 and 3 aren't valid values.

Any ways to validate if a value is array, without recursive rule applying?

Upvotes: 2

Views: 1153

Answers (1)

Gabriel
Gabriel

Reputation: 3867

As @zerkms said :

Zend_Filter_Input performs recursive traversing, so a particular validator can nothing to do with it.

To solve this problem, I'm using a "durty" way :

$input = new Zend_Filter_Input(
    array(
        'the_field_should_be_array'=> array(
             new MyPersonalValidator($this->_request->getParam('the_field_should_be_array')),
         )
    )
);


 class MyPersonalValidator extends Zend_Validate_Abstract{

    private $_paramIsValid;

public function __construct($param)
{
    $this->_paramIsValid = is_array($param);
}

public function isValid($not_usefull)
{
    if(!$this->_paramIsValid)
    {
        return false;
    }

    return true;
}}

Code explanation : I perform the validation of the field in the constructor of the validator. For this, It's needed to pass the field to the constructor and it not a good pratice but I didn't find another way.

Edit : The clean way is to extend Zend_Filter_Input to support the context. I never new why it wasn't implement before.

Upvotes: 1

Related Questions