G
G
Ghost26922018-01-31 15:19:03
Yii
Ghost2692, 2018-01-31 15:19:03

Why does a .csv file fail validation in Yii2?

Validation rules:

public function rules()
    {
        return [
            ['contact_file', 'file', 'skipOnEmpty' => false, 'extensions' => 'csv'],
        ];
    }

If you remove 'extensions' => 'csv' then it passes validation, why doesn't it pass validation with the CSV extension?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2018-01-31
@karminski

['contact_file', 'file', 'skipOnEmpty' => false, 'extensions' => ['csv']],

G
Ghost2692, 2018-01-31
@Ghost2692

The form:

<?php $form = ActiveForm::begin(['method' => 'post', 'id' => 'add-contacts-file', 'options' => ['class' => 'mt-2 mb-2 col-lg-4 col-xs-3', 'enctype' => 'multipart/form-data'] ]); ?>

                            <div class="custom-file">
                                <?= $form->field($addFileContact, 'contact_file')->fileInput(['class' => 'custom-file-input'])->label(Yii::t('app', 'Choose file'), ['class' => 'custom-file-label', 'for' => 'customFile']);
                                ?>

                                <div style="margin-top: -15px"><?= Yii::t('app', 'File type should be .csv') ?></div>

                            </div>

                            <?= Html::submitButton(Yii::t('app', 'Add contacts'), ['class' => 'mt-2 btn btn-sm button-success', 'form' => 'add-contacts-file']) ?>

                            <?php ActiveForm::end(); ?>

file csv
Povna model
/**
     * @var UploadedFile
     */
    public $contact_file;

    public function rules()
    {
        return [
            ['contact_file', 'file', 'skipOnEmpty' => false, 'extensions' => 'csv'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'contact_file' => 'Contact file',
        ];
    }

    public function uploadContacts()
    {
        if ($this->validate()) {
            $this->contact_file->saveAs('uploads/contacts/' . $this->contact_file->baseName . '.' . $this->contact_file->extension);
            return true;
        } else {
            return false;
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question