1

如果文件字段不为空,我正在尝试验证字段。因此,如果有人试图上传文件,我需要验证另一个字段以确保他们选择了他们正在上传的内容,但是我不知道如何查看或仅在字段不为空时运行规则。

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();
}

所以this->video无论我是否上传了东西,它总是空的。如何检查是否设置了该变量?

4

2 回答 2

2

必须正确定义自定义验证函数。它总是有两个参数$attribute& $params

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

现在,您应该编写自定义的验证方式。我相信那会很好。

于 2012-10-15T07:13:45.317 回答
0

您可以使用 jQuery/javascript 检查它,其中“new_document”是输入文件字段的名称。

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;
    }

这段代码显然不适合您的需求,但可能需要拼凑您需要的东西。

于 2012-10-14T21:46:44.007 回答