James McDonnell James McDonnell - 2 months ago 10
PHP Question

CakePhp Upload Validation

I've been trying to get this to work for a bunch of hours, countless googling has not resulted in anything helpful.

I was wondering if there was a way to validate on the variables inside of a form fileinput. So like in a form "upload" I want to make sure that upload[name] is not empty. Could I do this at all with Cakephp's model validation?

Answer

There is no way in Cakephp to validate fileinput field.

You can do it by custom validation rules like below example

for view file

<?php
    echo $this->Form->file('image');
    echo $this->Form->error('image');
?>

For model file

<?php
    public $validate = array(
        'image' => array(
            'rule' => array('chkImageExtension'),
            'message' => 'Please Upload Valid Image.'
        )
    );



    public function chkImageExtension($data) {
       $return = true; 

       if($data['image']['name'] != ''){
            $fileData   = pathinfo($data['image']['name']);
            $ext        = $fileData['extension'];
            $allowExtension = array('gif', 'jpeg', 'png', 'jpg');

            if(in_array($ext, $allowExtension)) {
                $return = true; 
            } else {
                $return = false;
            }   
        } else {
            $return = false; 
        }   

        return $return;
    }   
?>
Comments