0

I want to implement the jQuery Validation on the client. When a user is going to upload a file, the Jquery will check the size of the file and if it exceeds the max size, a user can not upload the file. How to do it using jQuery or jQuery Validate plugin?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Steven
  • 24,410
  • 42
  • 108
  • 130

3 Answers3

2

You can't do it with JQuery. The problem is that javascript can not access the file system.

Here is something you can read about the subject - Using jQuery, Restricting File Size Before Uploading

Community
  • 1
  • 1
Svetlozar Angelov
  • 21,214
  • 6
  • 62
  • 67
0

Jquery validation plugin code

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

Mahesh Lad
  • 1,997
  • 1
  • 9
  • 8
0

And a mere seven years later... I have a pull request in to validate the max size of a file (or a collection of files). It's under code review right now. See https://github.com/jquery-validation/jquery-validation/pull/2087

Rob Johnston
  • 859
  • 8
  • 21