JQuery中的多文件上载扩展验证

时间:2015-01-04 09:09:47

标签: javascript php jquery validation

我无法获得多文件上传的Exact验证。我的表格就像这样

 Upload Attachment(s):
    <input type="file" id="client_attachments" name="client_attachments[]" class="client_attachments">
    <div class="addbutn"><a href="javascript:void(0);" id="add_more"><i class="fa fa-plus-square"></i></a></div>
<div class="new_file"></div>

当我点击添加更多按钮时,它会添加多个文件uploads.Here js代码

$(document).ready(function(){
$('#add_more').click(function(){

$('.new_file').append('<div><input type="file" class="client_attachments" name="client_attachments[]"></div>');

});

我的问题是无法验证新添加的输入文件。我写了像这样的验证的JS代码

$('input[name="client_attachments[]"]').each(function(){
    var value=$(this).val;
    alert(value);
    $(value).checkFileType({
        allowedExtensions: ['jpg', 'jpeg','pdf','doc','docx','txt','png','bmp','gif','xlsx'],
        success: function() {
            alert('Success');
        },
        error: function() {
            alert('Error');
        }
    });


});

对于 checkFileType ,js函数是

(function($) {
    $.fn.checkFileType = function(options) {
        var defaults = {
            allowedExtensions: [],
            success: function() {},
            error: function() {}
        };
        options = $.extend(defaults, options);

        return this.each(function() {

            $(this).on('change', function() {
                var value = $(this).val(),
                    file = value.toLowerCase(),
                    extension = file.substring(file.lastIndexOf('.') + 1);

                if ($.inArray(extension, options.allowedExtensions) == -1) {
                    options.error();
                    $(this).focus();
                } else {
                    options.success();

                }

            });

        });
    };

})(jQuery);

它只验证一个文件。请帮我验证如何验证附加文件。提前谢谢。

1 个答案:

答案 0 :(得分:0)

HTML

&#13;
&#13;
$("input[name=file1]").change(function() {
    var names = [];
    for (var i = 0; i < $(this).get(0).files.length; ++i) {
        names.push($(this).get(0).files[i].name);
    }
    $("input[name=file]").val(names);
});
&#13;
<input type="file" id="foo" name="file1" multiple="multiple" />
<input name="file" type="text" />
&#13;
&#13;
&#13;