Validation of Image Size

Asked

Viewed 384 times

1

I am trying to use jQuery Validate plugin to validate a field file.

I just want to check the image size. If it is larger than 3mb it is not to submit the form.

Look at my code below:

$.validator.addMethod('filesize', function(value, element, param) {
    return this.optional(element) || (element.files[0].size >= param) 
});

if($("#form-ouvidoria")[0]){
   $("#form-ouvidoria").validate({
      rules             : {
        assunto         : "required",
        departamento    : "required",
        mensagem        : "required",
        field: { 
            required: true, 
            extension: "png|jpe?g|gif", 
            filesize: 3145728
        }
      },
      submitHandler: function(form){
        $("#enviaChamado").attr('disabled', 'true');
        $('span.loading').css('opacity', '1');
        form.submit();
      }
   });
}

But when selecting an image larger than 3mb and pressing on send gives the following error:

Uncaught Typeerror: Cannot read Property 'call' of Undefined. Exception occurred when checking element , check the 'Extension' method.

  • What kind of application "IDE" you are using?

  • Like this, @Marconciliosouza ?

  • Your jQuery , you’re using on a page aspx, php ... html .....

  • And what the server-side language influences in this ?

  • I had no influence on the answer, it was only a doubt of mine... but as you already have the answer blz.

  • It’s in PHP that I program.

Show 1 more comment

2 answers

2

I use the jQuery Fileupload to do this. Natively it already has this validation, and some other cool features.

$('#fileupload').fileupload({
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, // tipo de arquivos
    maxFileSize: 512000 // tamanho maximo
    [...]
});
  • Top, but it’s only for file ? Because jQuery Validate I use for forms. It’s very good too!

  • @Taopaipai, Fileupload is for files only, although it has events to handle when adding files, or before you start uploading. And at that moment you can call the jQuery Validity. Or use together the unobtrusive, which I like very much.

  • Who downgrade, can justify?

  • 1

    I don’t justify myself when I vote down. But I didn’t go, I gave vote up on your answer, if you want I send you print, print, scan, register and send you...

  • @Zooboomafoo haha, you don’t need it. I would just like to know, from whom you negatively, why. Because sometimes I really respodi something wrong, and I would like to learn tbm. But thanks for the return.

1


Corrected. I didn’t know, but I found on the internet that should import the following file:

jqueryvalidation.org/files/dist/additional-methods.min.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.