Reputation: 3710
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?
Upvotes: 0
Views: 4862
Reputation: 4869
@Sunman Singh's answer is not true anymore.
static Validation::extension(mixed $check, array $extensions = array('gif', 'jpeg', 'png', 'jpg'))
This rule checks for valid file extensions like
.jpg
or.png
. Allow multiple extensions by passing them inarray
form.
public $validate = array(
'image' => array(
'rule' => array(
'extension',
array('gif', 'jpeg', 'png', 'jpg')
),
'message' => 'Please supply a valid image.'
)
);
static Validation::fileSize($check, $operator = null, $size = null)
This rule allows you to check filesizes. You can use
$operator
to decide the type of comparison you want to use. All the operators supported bycomparison()
are supported here as well. This method will automatically handle array values from$_FILES
by reading from thetmp_name
key if$check
is anarray
and contains that key:
public $validate = array(
'image' => array(
'rule' => array('fileSize', '<=', '1MB'),
'message' => 'Image must be less than 1MB'
)
);
See the link below for references. Altough, I'd recommend writting your own function for more security but those can certainly save you some time
http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::extension
Upvotes: 0
Reputation: 1377
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;
}
?>
Upvotes: 5