提交表单之前验证文件扩展名和大小

问题描述 投票:0回答:7

我正在使用 jQuery 验证插件,并且想在提交表单之前验证文件扩展名和文件大小。

"use strict";
$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            filesize : 50000,
        }
    }
});

我想要与上面类似的代码。

jquery jquery-validate
7个回答
45
投票

您需要编写自定义规则来验证文件大小,文件扩展名也必须作为逗号分隔的字符串传递

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');

jQuery(function ($) {
    "use strict";
    $('#update_profile').validate({
        rules: {
            FirstName: {
                required: true,
                maxlength: 20
            },
            image: {
                required: true,
                extension: "jpg,jpeg",
                filesize: 5,
            }
        },
    });
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

<form id="update_profile" method="post" action="">
  <input type="file" name="image" />
  <input type="submit" value="Save" />
</form>


8
投票

请注意,element.files[0].size 使用字节单位。因此,如果您想使用 MB,则需要将其转换为字节。在这个例子中:

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param * 1000000)
}, 'File size must be less than {0} MB');

您需要传入您的验证:

$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            filesize : 5, // here we are working with MB
        }
    }
});

2
投票

$.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} MB');

jQuery(function ($) {
    "use strict";
    $('#update_profile').validate({
        rules: {
            FirstName: {
                required: true,
                maxlength: 20
            },
            image: {
                required: true,
                extension: "jpg,jpeg",
                filesize: 5,
            }
        },
    });
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

<form id="update_profile" method="post" action="">
  <input type="file" name="image" />
  <input type="submit" value="Save" />
</form>


1
投票
$.validator.addMethod('filesize', function (value, element, arg) {
            var minsize=1000; // min 1kb
            if((value>minsize)&&(value<=arg)){
                return true;
            }else{
                return false;
            }
        });

        $("#myform" ).validate({
            rules: {
                file_upload:{
                    required:true,
                    accept:"application/pdf,image/jpeg,image/png",
                    filesize: 200000   //max size 200 kb
                }
            },messages: {
                file_upload:{
                    filesize:" file size must be less than 200 KB.",
                    accept:"Please upload .jpg or .png or .pdf file of notice.",
                    required:"Please upload file."
                }
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

最小 1 kb 到最大 200 kb 文件大小并经过测试


1
投票

如果您使用

additional-methods.js
,您可以这样做:

$('#update_profile').validate({
    rules: {
        FirstName: {
            required: true,
            maxlength: 20
        },
        image: {
            required: true,
            extension: "jep | jpeg",
            maxsize: 50000,
        }
    }
});

-1
投票
 HTML


                <div class="col-sm-9 col-lg-6 col-xs-12 col-md-9">
                    <div class="input-group">
                        <input type="text" class="form-control"  name="uploadFile"  readonly id="uploadFile">
                        <span class="input-group-btn">
                            <span class="btn btn-primary btn-file">
                                Browse&hellip;  <input type="file" id="uploadFile" name="uploadFile" >         
                            </span>
                        </span>
                    </div>
                    <div id="spanUploadFile">

//Message will display here
                    </div>

                </div>


JQuery



 $(document).on('change', '.btn-file :file', function() {

        var input = $(this),numFiles = input.get(0).files ? input.get(0).files.length : 1,
                label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
        var msg = "spanUploadFile";
        input.trigger('fileselect', [numFiles, label]);
        genrateFileMsg(this.id, msg)
genrateSizeMsg(this.files[0], msg)


    });

 function genrateFileMsg(id, nId)
    {

        var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
        var fileExtensionDOB = ['pdf'];
        //var fileExtensionDOB = ['pdf', 'doc', 'docx', 'txt', ];

            if ($.inArray($("#" + id).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                $("#" + nId).html("Only files of type jpg, png, gif, jpeg is allowed");

                return false;
            }







        return true
    }
    function genrateSizeMsg(f, nId)
    {

        var f = f.size;


            f = f / 1024;

            if (f > 100)
            {
                $("#" + nId).html("The file you are trying to upload is too large (max 100KB)");
                return false;
            }



        return true;
    }

-1
投票

<!-- Size in kb -->
   $.validator.addMethod('filesize', function (value, element,param) {
   
  var size=element.files[0].size;
 
  size=size/1024;
  size=Math.round(size);
  return this.optional(element) || size <=param ;
  
}, 'File size must be less than {0}');

jQuery(function ($) {
    "use strict";
    $('#update_profile').validate({
        rules: {
            FirstName: {
                required: true,
                maxlength: 20
            },
            image: {
                required: true,
                extension: "jpg,jpeg",
                filesize: 1000
            }
        },
    });
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

<form id="update_profile" method="post" action="">
  <input type="file" name="image" />
  <input type="submit" value="Save" />
</form>

最大大小1000kb

© www.soinside.com 2019 - 2024. All rights reserved.