简体   繁体   English

Zend Framework 2中的自定义验证器

[英]Custom validator in zend framework 2

I am new to Zend framework. 我是Zend框架的新手。 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: 这是module.config.php文件代码:

'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: 要将验证器选项注入到构造函数方法中,您应在module.config.php文件中像这样注册验证器:

<?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: 在您的示例中,只需将完整路径添加到Validator即可:

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. 您需要使用FileInput()代替。

The simple example can be found here: https://framework.zend.com/manual/2.4/en/modules/zend.input-filter.file-input.html 可在此处找到简单的示例: https : //framework.zend.com/manual/2.4/en/modules/zend.input-filter.file-input.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM