views:

225

answers:

1

How to make file uploading as optional with validation? The code below validates even if i didn't selected any file. I want to check the extension only if i selected the the file. If i am not selecting any file it should not return any validation error.

class Catalog extends AppModel{
    var $name = 'Catalog';
    var $validate = array(
        'name' => array(
            'rule' => '/^[a-z0-9 ]{0,}$/i',
            'allowEmpty' => false,
            'message' => 'Invalid Catalog name'
        ),
        'imageupload' => array(
            'rule' => array('extension',array('jpeg','jpg','png','gif')),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'Invalid file'
        ),
       );
}

thanks in advance

+1  A: 

"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"

So by the time you save your data array, it looks something like this I assume:

array(
    'image' => 'foobar',
    'imageupload' => array(
        'name' => 'foobar',
        'size' => 1234567,
        'error' => 0,
        ...
     )
)

Which means, the imageupload validation rule is trying to work on this data:

array(
    'name' => 'foobar',
    'size' => 1234567,
    'error' => 0,
    ...
 )

I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".

Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.

deceze
which is the best practice???custom validation or some more processing in controller
RSK
Personally I would tinker with `$this->data` before saving it, although I think a custom rule would be better practise.
DavidYell
thankz deceze and david......i will go for custom validation
RSK