Skip to content Skip to sidebar Skip to footer

Checking Image Size Using Jquery Validation Not Working

I am uploading an image to the folder but before uploading, I am checking the image extension and size. I am using jQuery validation. I checked on SO before uploading the question

Solution 1:

Your parameter is only set to 5

$('#form').validate({rules: {
      image: {
        ....filesize:5,  ...

That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB. Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.

Try 5242880 if you want to allow files under 5 MB.

filesize: 5242880// <- 5 MB

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

$(function($) {
  "use strict";
  $('#form').validate({
    rules: {
      image: {
        //required: true,extension: "jpg,jpeg,png",
        filesize: 5242880// <- 5 MB
      }
    },
  });
});
<formid="form"method="post"action=""><inputtype="file"name="image" /><inputtype="submit"value="Upload" /></form><scripttype="text/javascript"src="//code.jquery.com/jquery-1.11.3.js"></script><scripttype="text/javascript"src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script><scripttype="text/javascript"src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>

Solution 2:

Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly. For example if you want to check if the file size is less than 5MB, you should use

image: {
  extension: "jpg,jpeg,png",
  filesize: 5*1024*1024,
}

Post a Comment for "Checking Image Size Using Jquery Validation Not Working"