限制jQuery验证中文件上传的文件扩展名

5

我希望使用jQuery Validation插件对input type="file"进行验证。我想要限制文件格式为doc,pdf,rtf和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
看起来不错。http://jsfiddle.net/arunpjohny/Jq93a/1/ - Arun P Johny
谢谢Arun,我改变了我的问题。 - Sarath Babu Nuthimadugu
你的代码可以运行,那么问题到底出在哪里呢?你记得要包含 additional-methods.js 文件吗? - Sparky
3个回答

13
你没有解释你的代码出了什么问题:
$("#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/


谢谢,Sparkly。我在我的应用程序中写了相同的代码,它只接受PDF文件。如果我们包含DOC文件,它会显示错误。 - Sarath Babu Nuthimadugu
@sarath,我的演示非常完美,所以问题与你向我们展示的任何代码无关。 - Sparky
我尝试实现这个演示,但它没有工作。就像这里我已经实现了jquery.min、jquery.validate和additional-extension.js,但仍然没有工作。是否还需要添加其他东西? - user2089987
@user2089987,"not working" 到底是什么意思?你有查看错误控制台吗? - Sparky

3

如果您不想创建规则

只需在输入框中使用以下accept属性即可

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


(注:该代码是用于选择文件上传的,accept属性用于指定文件类型,多个文件类型之间用逗号分隔)

2
用户可以在对话框中更改文件类型,因此最好进行额外的验证。 - Christopher Grigg

0
今天我需要那个脚本,但是我找不到它了。于是我自己写了一个脚本(几乎适用于所有浏览器,甚至IE)。我想提醒大家我是jQuery的初学者,但我正在尝试做一些新的东西:

打开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>

如果我的代码有任何错误,请告诉我 :) 谢谢。

此外,我可以在评论中回答问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接