John Dorean
John Dorean

Reputation: 3874

CakePHP validation not detecting form field

I have a form where users can upload images, and I'm printing it to the page like so:

<?php echo $this->Form->label('file', 'Image file', array('class' => 'col-lg-1 control-label')); ?>

Then, in the model I'm setting up validation like so:

public $validate = array(
    'file' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'You must select an image to upload'
        ),
        'extension' => array(
            'rule' => array('extension', array('png')),
            'message' => 'Images must be in PNG format'
        ),
        'size' => array(
            'rule' => array('fileSize', '<', '1MB'),
            'message' => 'Images must be no larger than 1MB'
        ),
        'goodUpload' => array(
            'rule' => 'uploadError',
            'message' => 'Something went wrong with the upload, please try again'
        )
    )
);

However, Cake doesn't seem to be associating the form field with the validation rule, as if I select an image to upload I always get "You must select an image to upload" as a form error. I've made sure the form has enctype="multipart/form-data".

Is this happening because file isn't a database field? How can I make cake run some validation on file?

Edit: Here's my entire form, as requested: http://pastebin.com/SbSbtDP9

Upvotes: 0

Views: 830

Answers (2)

John Dorean
John Dorean

Reputation: 3874

Managed to figure it out. Turns out having the notEmpty validation on a file fieldnever works, it always thinks there's nothing there and so always throws that validation message.

Worked around it by writing my own validation method.

Upvotes: 0

Brett Stewart
Brett Stewart

Reputation: 478

You can validate fields that are not in the database, long as you have the correct field name in the correct model.

From what I can see in your code it seems your outputting a label instead of an actual input, for the image upload I would try

echo $this->Form->create('Model', array('type'=>'file'));
echo $this->Form->input('file', array('type'=>'file'));
echo $this->Form->submit('Upload Image'):
echo $this->Form->end();

For the validation I would try something like with the rest of your validate options (size, etc...) CakePHP usually throws an error on notEmpty on File Uploads. So just checking for the extension type is usually good enough.

public $validate = array(
   'file' => array(
     'rule' => array(
     'extension', array('jpeg', 'jpg')
     'message' => 'You must supply a file.'
     )
   )
);

Majority of time in CakePHP for Image Uploading I resort to a plugin such as https://github.com/josegonzalez/cakephp-upload it does validation and upload handling all in one.

Upvotes: 1

Related Questions