How can I validate the maximum file size is 2 mb per file for multiple files? (vuetify)

Total
7
Shares

I’m trying to setup a validation rule on Vuetify’s v-file-input to limit file sizes to 2MB, but the validation incorrectly fails (and the input error appears) when I select files under 2MB.

Excerpt of my Codepen:

<v-file-input
  multiple
  :rules="rules"
  accept="image/jpg, image/jpeg, application/pdf"
  placeholder="Pick an avatar"
  prepend-icon="mdi-camera"
  label="Avatar"
></v-file-input>

<script>
  //...
  data: () => ({
    rules: [
      value => !value || value.size < 2000000 || 'Avatar size should be less than 2 MB!',
    ],
  }),
  //...
</script>

How do I solve this problem?


Solution

The problem is your v-file-input accepts multiple files, so the argument of the validation rule is actually an array of File object(s) (even if only one file selected). The rule function should look similar to this:

files => !files || !files.some(file => file.size > 2e6) || 'Avatar size should be less than 2 MB!'

The rule uses Array.prototype.some on the files array to determine if any of the file sizes are over 2 * 10^6. However, since file sizes are in terms of bytes, I recommend comparing to 2MiB instead (i.e., 2 * 1024 * 1024 = 2_097_152).

Demo:

_x000D_

_x000D_

new Vue({_x000D_
  el: '#app',_x000D_
  vuetify: new Vuetify(),_x000D_
  data: () => ({_x000D_
    rules: [_x000D_
      files => !files || !files.some(file => file.size > 2_097_152) || 'Avatar size should be less than 2 MB!'_x000D_
    ],_x000D_
  }),_x000D_
})

_x000D_

<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/dist/vuetify.js"></script>_x000D_
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vuetify.min.css">_x000D_
<link rel="stylesheet" href="https://unpkg.com/@mdi/[email protected]/css/materialdesignicons.min.css">_x000D_
_x000D_
<div id="app">_x000D_
  <v-app id="inspire">_x000D_
    <v-file-input_x000D_
      multiple_x000D_
      :rules="rules"_x000D_
      accept="image/jpg, image/jpeg, application/pdf"_x000D_
      placeholder="Pick an avatar"_x000D_
      prepend-icon="mdi-camera"_x000D_
      label="Avatar"_x000D_
    ></v-file-input>_x000D_
  </v-app>_x000D_
</div>

_x000D_

_x000D_

_x000D_

Leave a Reply

Your email address will not be published. Required fields are marked *