Image Size Validation

1

I'm trying to use the jQuery Validate plugin to validate a file field.

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

See 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 you select an image larger than 3mb and push on send it gives the following error:

  

Uncaught TypeError: Can not read property 'call' of undefined. Exception occurred when checking element, check the 'extension' method.

    
asked by anonymous 27.11.2015 / 18:53

2 answers

1

Fixed. I did not know, but I found on the internet that the following file should be imported:

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

    
27.11.2015 / 19:09
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
    [...]
});
    
27.11.2015 / 19:12