Zend framework 2 how use validator chains in fieldsets

6.1k Views Asked by At

I need to use validator chains in the getInputFilterSpecification method of the fieldset to use the breakChainOnFailure parameter and get only one error message.

I know make validator chains using InputFilter classes how explain the zend documentation, e.g.

    $input = new Input('foo');
    $input->getFilterChain()
          ->attachByName('stringtrim', true)  //here there is a breakChainOnFailure
          ->attachByName('alpha');

But I want make the same using the factory format. Where can I put the breakChainOnFailure parameter in this sample:

    $factory = new Factory();
    $inputFilter = $factory->createInputFilter(array(
        'password' => array(
            'name'       => 'password',
            'required'   => true,
            'validators' => array(
                array(
                    'name' => 'not_empty',
                ),
                array(
                    'name' => 'string_length',
                ),
            ),
        ),
    ));
2

There are 2 best solutions below

1
On

To answer your question we need to look at the InputFilter Factory, there we find the populateValidators method. As you can see, for validators it's looking for a break_chain_on_failure key in the spec. You just need to add that to your validator spec array...

$factory = new Factory();
$inputFilter = $factory->createInputFilter(array(
    'password' => array(
        'name'       => 'password',
        'required'   => true,
        'validators' => array(
            array(
                'name' => 'not_empty',
                'break_chain_on_failure' => true,
            ),
            array(
                'name' => 'string_length',
            ),
        ),
    ),
));

By the way, the attachByName method signatures for FilterChain (here) and ValidatorChain (here) are not the same. In your first example you're calling the method on a filter chain, which doesn't support break on failure at all. (you might also note that it's the third parameter of the validator chain method and not the second)

0
On

Reviewing my code, I would need to use the break_chain_on_failure parameter in a validation chain specification using instances of validator classes (not factory specifications).

view example:

    'password' = array(
        'required' => true,
        'validators' => array(
            new NotEmpty(),  //these are validator instace classes
            new HostName(),  //and them may be declared before
        ),
    );