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 validation plugin?
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
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
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
来源:https://stackoverflow.com/questions/1872486/how-to-check-the-size-of-an-uploaded-file-using-jquery-and-jquery-form-validatio