简体   繁体   中英

How to validate an array of uploaded files?

To validate a single file (a single input-file-field) is no problem in Yii and it works very well:

public function rules() {
    return CMap::mergeArray(parent::rules(), array(
        array(
            'image', 
            'file', 
            'allowEmpty'=>false, 
            'types'=>'pdf,jpg,gif,png', 
            'on' => 'CaseA, CaseB', 
            'maxSize'=>1024000, 
            'tooLarge' => 'Max File size is 1MB', 
            'message' => 'You have to upload a file at least'
        ),
        ....
        ....

What if image is an array of files? Created Form-Elements by Yii looks like this (Firebug-Output):

<input type="file" id="MyFormModel[image][0]" name="MyFormModel[image][0]">
<input type="file" id="MyFormModel[image][1]" name="MyFormModel[image][1]">

What exactly should I modify in my rules? A simple "image[]" does not help.

EDIT: Solution

public function rules() {
    return CMap::mergeArray(parent::rules(), array(
        array(
            'image', 
            'file', 
            'allowEmpty'=>false, 
            'types'=>'pdf,jpg,gif,png', 
            'on' => 'CaseA, CaseB', 
            'maxSize'=>1024000, 
            'maxFiles' => 5, // <----- THAT'S IT
            'tooLarge' => 'Max File size is 1MB', 
            'message' => 'You have to upload a file at least'
        ),
        ....
        ....

Set the maxFiles attribute appropriately and the validator will work for all of the inputs. You don't need to change the input control names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM