keeg
keeg

Reputation: 3978

Validate another field if file field is not empty

I'm trying to validate a field if a file fields is not empty. So if someone is trying to upload a file, I need to validate another field to make sure they selected what they are uploading, however I don't know how to check to see, or run a rule only if the field is not empty.

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('full_name, gender_id','required'),
        array('video', 'file', 'types'=>'mp4', 'allowEmpty' => true),
        array('audio', 'file', 'types'=>'mp3', 'allowEmpty' => true),
        array('video','validateVideoType'),
    );
}

public function validateVideoType() {
    print_r($this->video);
    Yii::app()->end();
}

So this->video is always empty whether I just uploaded something or not. How do I check to see if that variable is set?

Upvotes: 1

Views: 860

Answers (2)

Onkar Janwa
Onkar Janwa

Reputation: 3950

Custom validation function must be defined properly. It has two parameters always $attribute & $params.

public function validateVideoType($attribute, $params) {
    print_r($this->video);
    Yii::app()->end();
}

Now in this you should write your custom way to validate. I am sure that would work fine.

Upvotes: 2

Anthony
Anthony

Reputation: 658

You can check it with jQuery/javascript, where 'new_document' is the name of the input file field.

if ($("#new_document").val() != "" || $("#new_document").val().length != 0) {
        //File was chosen, validate requirements
        //Get the extension
        var ext = $("#new_document").val().split('.').pop().toLowerCase();
        var errortxt = '';
        if ($.inArray(ext, ['doc','docx','txt','rtf','pdf']) == -1) {
            errortxt = 'Invalid File Type';
            //Show error
            $("#document_errors").css('display','block');
            $("#document_errors").html(errortxt);

            return false;
        }

        //Check to see if the size is too big
        var iSize = ($("#new_document")[0].files[0].size / 1024);
        if (iSize / 1024 > 5) {
            errortxt = 'Document size too big. Max 5MB.';
            //Show error
            $("#document_errors").css('display','block');
            $("#document_errors").html(errortxt);

            return false
        }
    } else {
        //No photo chosen
        //Show error
        $("#document_errors").css('display','block');
        $("#document_errors").html("Please choose a document.");
        return false;
    }

This code is obviously not perfect for your needs but may have the requirements to piece together what you need.

Upvotes: 0

Related Questions