Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - Validate file size requirement in form file upload

I am using a Bootstrap Vue form to make a simple form where user can upload a file. Is there a way to validate the size of files selected using Vue form ?

I want to prevent user from uploading such files.

I have seen this solution but looks like it includes some third party plugin. I prefer a solution which doesn't

like image 323
MSS Avatar asked Sep 03 '18 04:09

MSS


1 Answers

Here's a generic Vue example of how to validate the file's size before the form is submitted.

The crux is obtaining the file object from the files property on the input itself, and checking the file's size via the size property; the rest is just stuff related to preventing the form from being submitted if the validation fails.

It goes without saying, but it is important that any kind of input validation such as this should be done on the server first and foremost; client-side validation enhances the user experience but provides no security.

new Vue({
  el: '#app',
  methods: {
    onSubmit(e) {
      const file = this.$refs.file.files[0];
      
      if (!file) {
        e.preventDefault();
        alert('No file chosen');
        return;
      }
      
      if (file.size > 1024 * 1024) {
        e.preventDefault();
        alert('File too big (> 1MB)');
        return;
      }
      
      alert('File OK');
    },
  },
});
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>

<div id="app">
  <form @submit="onSubmit">
    <input type="file" ref="file">
    <button type="submit">Submit</button>
  </form>
</div>
like image 52
Decade Moon Avatar answered Oct 15 '22 23:10

Decade Moon