【问题标题】:Custom validator in zend framework 2Zend 框架 2 中的自定义验证器
【发布时间】:2017-05-06 14:31:10
【问题描述】:

我是 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' 
         ),
    ),

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

【问题讨论】:

    标签: php validation zend-framework zend-framework2


    【解决方案1】:

    要将验证器选项注入到您的构造方法中,您应该像这样在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
            )
        ),
    
        //...
    
    );
    

    【讨论】:

    • :) 感谢您的回复。你能建议我如何在控制器操作中获取新上传的文件名吗?我正在使用验证规则,例如.. 'validators' => [ [ 'name' => '\User\Validator\ImageValidator', 'options' => [ 'minSize' => '1', 'maxSize' => '1024', 'newFileName' => time() 。 'newFileName2', 'uploadPath' => getcwd() 。 '/public/uploads/platform/' ], ], ],它工作正常,但我不知道如何在控制器操作中获取文件名或错误。
    • @anil 欢迎您。这应该被视为一个新问题。我建议您接受我的回答并在 StackOverflow 上提出一个新问题,如果您找不到已经处理此重命名问题的现有问题。您还可以查看我在另一个相关答案here 中引用的文档。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 2013-02-01
      • 2012-07-26
      • 1970-01-01
      相关资源
      最近更新 更多