Validate file extension and size before submitting form

后端 未结 7 1532
無奈伤痛
無奈伤痛 2020-12-30 06:51

I am using jQuery validate plugin, and want to validate file extension and file size before submitting a form.

\"use strict\";
$(\'#update_profile\').validat         


        
相关标签:
7条回答
  • 2020-12-30 07:21
     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;
        }
    
    0 讨论(0)
  • 2020-12-30 07:29

    $.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>

    0 讨论(0)
  • 2020-12-30 07:35

    <!-- 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>

    Max size 1000kb

    0 讨论(0)
  • 2020-12-30 07:40
    $.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();
                }
            });
    

    Min 1 kb to max 200 kb file size and it is tested

    0 讨论(0)
  • 2020-12-30 07:40

    If you're using additional-methods.js, you can do it like this:

    $('#update_profile').validate({
        rules: {
            FirstName: {
                required: true,
                maxlength: 20
            },
            image: {
                required: true,
                extension: "jep | jpeg",
                maxsize: 50000,
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-30 07:41

    Be aware that element.files[0].size works with byte unit. So if you want to work with MB, you need to convert it to bytes. In this example:

    $.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');
    

    You need to pass into your validate:

    $('#update_profile').validate({
        rules: {
            FirstName: {
                required: true,
                maxlength: 20
            },
            image: {
                required: true,
                extension: "jep | jpeg",
                filesize : 5, // here we are working with MB
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题