简体   繁体   中英

Custom validator in zend framework 2

I am new to Zend framework. I'm using custom validators to validate image file but I'm getting this error.

Zend\Validator\ValidatorPluginManager::get was unable to fetch or create an instance for ImageValidator

Here is validation file:

namespace User\Validator;

//use User\Validator\FileValidatorInterface;
use Zend\Validator\File\Extension;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\FilesSize;
use Zend\Filter\File\Rename;
use Zend\Validator\File\MimeType;
use Zend\Validator\AbstractValidator;

class ImageValidator extends AbstractValidator
{  
    const FILE_EXTENSION_ERROR  = 'invalidFileExtention';
    const FILE_NAME_ERROR       = 'invalidFileName'; 
    const FILE_INVALID          = 'invalidFile'; 
    const FALSE_EXTENSION       = 'fileExtensionFalse';
    const NOT_FOUND             = 'fileExtensionNotFound';
    const TOO_BIG               = 'fileFilesSizeTooBig';
    const TOO_SMALL             = 'fileFilesSizeTooSmall';
    const NOT_READABLE          = 'fileFilesSizeNotReadable';

    public $minSize = 64;               //KB
    public $maxSize = 1024;             //KB
    public $overwrite = true;
    public $newFileName = null;
    public $uploadPath = './data/';
    public $extensions = array('jpg', 'png', 'gif', 'jpeg');
    public $mimeTypes = array(
            'image/gif',
            'image/jpg',
            'image/png',
    );

    protected $messageTemplates = array(   
            self::FILE_EXTENSION_ERROR  => "File extension is not correct", 
            self::FILE_NAME_ERROR       => "File name is not correct",  
            self::FILE_INVALID          => "File is not valid", 
            self::FALSE_EXTENSION       => "File has an incorrect extension",
            self::NOT_FOUND             => "File is not readable or does not exist", 
            self::TOO_BIG               => "All files in sum should have a maximum size of '%max%' but '%size%' were detected",
            self::TOO_SMALL             => "All files in sum should have a minimum size of '%min%' but '%size%' were detected",
            self::NOT_READABLE          => "One or more files can not be read", 
    );

    protected $fileAdapter;

    protected $validators;

    protected $filters;

    public function __construct($options)
    {
        $this->fileAdapter = new Http();  
        parent::__construct($options);
    }

    public function isValid($fileInput)
    {   
        //validation code
    } 

}

and here is form file:

namespace User\Form;

use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\Session\Container;
use User\Validator\ImageValidator;

class PlatFormForm extends Form
{
    public function __construct()
    {
        parent::__construct('platform-form');
        $this->addInputFilter();
        $this->setAttribute('method', 'post'); 
        $this->setAttribute('enctype','multipart/form-data');
        $this->setAttribute('class', 'platform_popup');

        $this->addElements(); 
    }

    private function addElements() 
    {
        $this->add([
                'type'  => 'file',
                'name' => 'input_thumb',
                'attributes' => [                
                    'id' => 'input_thumb', 'class' => 'upload'
                ]               
            ]);

        $this->add([
                'type'  => 'submit',
                'name' => 'submit',
                'attributes' => [                
                    'id' => 'add_platform', 'class' => 'upload'
                ],
                'options' => [
                    'label' => 'CREATE',
                    //'label_attributes' => [

                    //],
                ],              
            ]);
    }   

    private function addInputFilter() 
    {
        $inputFilter = new InputFilter();        
        $this->setInputFilter($inputFilter);

        $inputFilter->add([
            'name'     => 'input_thumb',
            'required' => true,
            'filters'  => [
               ['name' => 'StringTrim'],
               ['name' => 'StripTags'],
            ],                
            'validators' => [
               [
                'name' => 'ImageValidator',
                  'options' => [
                    'minSize' => '64',
                    'maxSize' => '1024',
                    'newFileName' => 'newFileName2',
                    'uploadPath' => './data/'
                  ],
               ],              
            ],
          ]
        );      


    }  
}

and here is module.config.php file code:

'validators' => array(
        'invokables' => array(
            'ImageValidator' => 'User\Validator\ImageValidator' 
         ),
    ),

Can anyone suggest me what am I doing wrong?

To inject the validator options into your constructor method you should register your validator like this inside your module.config.php file:

<?php
use Zend\ServiceManager\Factory\InvokableFactory;
use User\Validator\ImageValidator;

return array(

    //...

    'validators' => array(
        'factories' => array(
            ImageValidator::class => InvokableFactory::class 
        ),
        'aliases' => array(
            'ImageValidator' => ImageValidator::class
        )
    ),

    //...

);

Actually, I ran into the same problem, and first of all you don't need to inject anything ( unless you want to ). Just by adding the full path to the Validator will work, in your example:

private function addInputFilter() 
    {
        $inputFilter = new InputFilter();        
        $this->setInputFilter($inputFilter);

        $inputFilter->add([
            'name'     => 'input_thumb',
            'required' => true,
            'filters'  => [
               ['name' => 'StringTrim'],
               ['name' => 'StripTags'],
            ],                
            'validators' => [
               [
                'name' =>'User\Validator\ImageValidator\ImageValidator',
                  'options' => [
                    'minSize' => '64',
                    'maxSize' => '1024',
                    'newFileName' => 'newFileName2',
                    'uploadPath' => './data/'
                  ],
               ],              
            ],
          ]
        );      
    }  

But I would like to point out that this is not the correct way of uploading files, regardless if they are images or not. You need to use FileInput() instead.

The simple example can be found here: https://framework.zend.com/manual/2.4/en/modules/zend.input-filter.file-input.html

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