cakePHP可选验证文件上传 [英] cakePHP optional validation for file upload
问题描述
如何将文件上传为可选的验证?
即使我没有选择任何文件,下面的代码也会验证。
我想检查扩展名,只有当我选择了该文件。
如果我不选择任何文件,它不应该返回任何验证错误。
class Catalog extends AppModel {
var $ name ='Catalog';
var $ validate = array(
'name'=> array(
'rule'=>'/ ^ [a-z0-9] {0,} $ / i' ,
'allowEmpty'=> false,
'message'=>'无效的目录名称'
),
'imageupload'=& 'rule'=> array('extension',array('jpeg','jpg','png','gif')),
'required'=> false,
'allowEmpty '=> true,
'message'=>'无效的文件'
),
);提前感谢
$ b html]'[$''''= $ this-> data'''''''''''' imageupload'] ['name'];
所以当你保存数据数组时, :
array(
'image'=>'foobar',
'imageupload'=> ; array(
'name'=>'foobar',
'size'=> 1234567,
'error'=> 0,
...
)
这意味着 imageupload 验证规则正在尝试处理此数据:
数组(
'name'=> ;'foobar',
'size'=> 1234567,
'error'=> 0,
...
)
它试图验证的值是一个数组的东西,而不只是一个字符串。这不太可能通过指定的验证规则。它也可能永远不是空。
您可以创建一个可以处理此数组的自定义验证规则,或者您需要在尝试之前在控制器中进行一些更多的处理以验证它。
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
解决方案
"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.
这篇关于cakePHP可选验证文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文