CakePHP 3. Validation of uploaded file extension

前提是你 提交于 2020-01-04 05:52:06

问题


I am using CakePHP 3. I have the upload field and want to permit uploading only .pdf and .doc(x) files. How can I add that properties to the following validator?

$validator
   ->notEmpty('article');

回答1:


Simply add the extension rule in your validation which is define in http://api.cakephp.org/3.0/class-Cake.Validation.Validation.html

extension( string|array $check , array $extensions ['gif', 'jpeg', 'png', 'jpg'] )

example:

$validator
            ->allowEmpty('profile_image')
            ->add('profile_image', [
                'validExtension' => [
                    'rule' => ['extension',['png']], // default  ['gif', 'jpeg', 'png', 'jpg']
                    'message' => __('These files extension are allowed: .png')
                ]
    ]);



回答2:


You have to add rule to your validator:

$validator
        ->notEmpty('avatar', __('Please enter your cute picture'))
        ->requirePresence('avatar', 'create')
        ->add('avatar', 'validFormat', [
            'rule' => ['custom', '([^\s]+(\.(?i)(pdf|doc|docx))$)'], 
            'message' => __('These files extension are allowed: .pdf, .doc, .docx')
        ]);



回答3:


Using allowEmpty('profile_image') might give you some issues since it's a field of type 'file'.

Maybe you better look at the uploadedFile rule with optional true parameter.



来源:https://stackoverflow.com/questions/33432934/cakephp-3-validation-of-uploaded-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!