zend框架2中的自定义验证器

时间:2016-12-21 08:22:14

标签: php validation zend-framework zend-framework2

我是Zend框架的新手。我使用自定义验证程序来验证图片文件,但我收到了此错误。

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

这是验证文件:

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
    } 

}

这里是表单文件:

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/'
                  ],
               ],              
            ],
          ]
        );      


    }  
}

这里是module.config.php文件代码:

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

有谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:0)

要将验证器选项注入构造函数方法,您应该在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
        )
    ),

    //...

);

答案 1 :(得分:0)

实际上,我遇到了同样的问题,首先你不需要注入任何东西(除非你想要)。在您的示例中,只需添加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/'
                  ],
               ],              
            ],
          ]
        );      
    }  

但我想指出,这不是上传文件的正确方法,无论它们是否是图像。您需要改为使用 FileInput()

这个简单的例子可以在这里找到:https://framework.zend.com/manual/2.4/en/modules/zend.input-filter.file-input.html