phpvalidationzend-framework2extract-error-message

ZF2 File validators return all messages but need only triggered


I want to get only triggered messages, but I am getting all registred messages.

$inputFilter = $factory->createInput(array(
        'name'       => 'image',
        'required'   => true,
        'validators' => array(
            array(
                'name'    => '\Zend\Validator\File\IsImage',
                'options' => ['message' => 'File has to be valid image.']
            ),
            array(
                'name'    => '\Zend\Validator\File\Extension',
                'options' => ['extension' => 'png,jpg,jpeg', 'message' => 'Image extension has to be png,jpg or jpeg.'],
            ),
            array(
                'name'    => '\Zend\Validator\File\Size',
                'options' => ['max' => '2MB', 'message' => 'Maximum file size for image is 2MB.'],
            ),
        ),
    ));

later in controller:

if(!$filter->isValid()){
    var_dump($filter->getMessages());
}

If I try to upload image of 5MB size I am getting all messages:

array(
  'image' => array(
    'fileIsImageNotReadable' => 'File has to be valid image'
    'fileExtensionNotFound' => 'Image extension has to be png,jpg or jpeg'
    'fileSizeNotFound' => 'Maximum file size for image is 2MB'  
  )
);

But expect only "Maximum file size for image is 2MB".

Is there any way to return only triggered messages? Does that should be default behavior of the getMessages() method?


Solution

  • A possible solution for that is to use the Validator Chains.

    In some cases it makes sense to have a validator break the chain if its validation process fails. Zend\Validator\ValidatorChain supports such use cases with the second parameter to the attach() method. By setting $breakChainOnFailure to TRUE, the added validator will break the chain execution upon failure, which avoids running any other validations that are determined to be unnecessary or inappropriate for the situation.

    This way, validation stops at the first failure and you'll only have the message where validation fails. You could also set priorities so that your validators would be applied in a particular order. This example given on the documentation uses the method attach. This is not what you need exactly.

    In your case, you could just use the break_chain_on_failure key in your validator spec with a value set to true. Something like this :

    $inputFilter = $factory->createInput(array(
            'name'       => 'image',
            'required'   => true,
            'validators' => array(
                array(
                    'name'    => '\Zend\Validator\File\IsImage',
                    'options' => ['message' => 'File has to be valid image.']
                    'break_chain_on_failure' => true,
                ),
            ),
    ));