Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty values passed to Zend framework 2 validators

How can I pass an empty value through Zend framework 2 ValidatorChain to my custom validator?

It was possible on ZF1 by allowEmpty(false)

On ZF2 with empty element value :

  • If allowEmpty = false, NotEmptyValidator is added to the top of ValidatorChain with breakOnFailure = true, @see Zend/InputFilter/Input#injectNotEmptyValidator.

  • If allowEmpty = true, Element is considered as Valid, @see Zend/InputFilter/BaseInputFilter#isValid

    if ($input->allowEmpty()) {
        $this->validInputs[$name] = $input;
        continue;
    }
    
like image 503
deyine Avatar asked Feb 16 '13 12:02

deyine


1 Answers

continue_if_empty solved my problem. Thanks to @dson-horácio-junior. This is what I used:

$this->add(array(
    'name' => 'field',
    'continue_if_empty' => true,
    'filters' => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim')
    ),
    'validators' => array(
        array(
            'name' => 'Application\Form\Validator\Sample'
        )
    )
));

public function isValid($value, $context = null)
{
    if ($value == '' && $context['otherfield'] == '') {
        $this->error(self::INVALID_FIELD);

        return false;
    }

    // ...
}
like image 83
anilyeni Avatar answered Sep 19 '22 18:09

anilyeni