在jQuery Validation中限制上传到文件扩展名

时间:2013-12-14 09:40:12

标签: jquery jquery-validate

我想使用input type="file"的jQuery Validation插件执行验证。我想将文件格式限制为doc,pdf,rtf, and docx

这是我的代码:

  $("#contact-form").validate({ 
          onfocusout: function(e) {
              this.element(e);
            },
        rules:{

            resume:{
                required:true,
                extension: "docx|rtf|doc|pdf"
            }

        },
    resume:{
                required:"input type is required",                  
                extension:"select valied input file format"
            }


    });

3 个答案:

答案 0 :(得分:8)

您从未解释过您使用代码时遇到的问题:

$("#contact-form").validate({ 
    onfocusout: function(e) {
        this.element(e);
    },
    rules:{
        resume:{
            required:true,
            extension: "docx|rtf|doc|pdf"
        }
    },
    resume:{
        required:"input type is required",                  
        extension:"select valied input file format"
    }
});

但是,您在不使用messages选项的情况下声明邮件。这是一个可能会破坏插件的错误,或者至少会忽略您的自定义错误消息。

您的代码应如下所示......

$("#contact-form").validate({ 
    onfocusout: function(e) {  // this option is not needed
        this.element(e);       // this is the default behavior
    },
    rules:{
        resume:{
            required:true,
            extension: "docx|rtf|doc|pdf"
        }
    },
    messages: {  // <-- you must declare messages inside of "messages" option
        resume:{
            required:"input type is required",                  
            extension:"select valid input file format"
        }
    }
});

工作演示:http://jsfiddle.net/ZqxR2/

答案 1 :(得分:3)

如果您不想创建规则

只需在输入中使用accept属性,如下所示

<input type="file" accept="doc,pdf,rtf,docx"/>

答案 2 :(得分:0)

今天,我需要该脚本,但找不到。我制作了自己的脚本(几乎适用于所有浏览器,甚至IE)。我想知道我是jQuery的初学者,但是我正在尝试做一些新的事情:

Oppen JSfiddle

例如:

$('#file').on('change', function() {
 var numb = $(this)[0].files[0].size/1024/1024; //count file size
var resultid = $(this).val().split(".");
var gettypeup  = resultid [resultid.length-1]; // take file type uploaded file
var filetype = $(this).attr('data-file_types'); // take allowed files from input
var allowedfiles = filetype.replace(/\|/g,', '); // string allowed file
var tolovercase = gettypeup.toLowerCase();
var filesize = 2; //2MB
var onlist = $(this).attr('data-file_types').indexOf(tolovercase) > -1;
var checkinputfile = $(this).attr('type');
numb = numb.toFixed(2);

if (onlist && numb <= filesize) {
			$('#alert').html('The file is ready to upload').removeAttr('class').addClass('xd2'); //file OK
   } else {
   if(numb >= filesize && onlist){
  $(this).val(''); //remove uploaded file
      $('#alert').html('Added file is too big \(' + numb + ' MB\) - max file size '+ filesize +' MB').removeAttr('class').addClass('xd'); //alert that file is too big, but type file is ok
      } else if(numb < filesize && !onlist) {
     $(this).val(''); //remove uploaded file
      $('#alert').html('An not allowed file format has been added \('+ gettypeup +') - allowed formats: ' + allowedfiles).removeAttr('class').addClass('xd'); //wrong type file
      } else if(!onlist) {
    $(this).val(''); //remove uploaded file
      $('#alert').html('An not allowed file format has been added \('+ gettypeup +') - allowed formats: ' + allowedfiles).removeAttr('class').addClass('xd'); //wrong type file
      }
   }
})
body{background:#fff}

#alert.xd{background:#ff9e9e; border:1px solid #ff0000;
color: #000;
padding:5px;
border-radius:10px}

#alert.xd2{background:#9effb3; border:1px solid #00de26;
color: #000;
padding:5px;
border-radius:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<br>
<input type="file" id="file" data-file_types="pdf|doc|docx|rtf|odt|jpg|jpeg">
<br><br>
Allowed files:<br><br>
<div id="allowed-files"></div>
<br><br>
<div id="allowed-size"></div>

<div id="alert"></div>
<script>
var title = $( "#file" ).attr( "data-file_types" ).replace(/\|/g,', ');
$( "#allowed-files" ).text( title );
</script>

如果我的代码中有一些错误,请告诉我:)谢谢。

我也可以在评论中回答问题。