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
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
Share Improve this question asked Sep 3, 2018 at 4:02 MSSMSS 1251 gold badge2 silver badges9 bronze badges 3- Validation, particularly this type of validation, should be performed on the receiving server and errors sent back and displayed by the client. The client should not be responsible for validating user input; keep in mind that your application is not the only door to your server. – Marty Commented Sep 3, 2018 at 4:58
- @Marty Yeah thanks I did not think about the possibility of other clients. But what do you mean by "...particularly this type of validation..." ? What is different about files that a server validation is preferable ? I mean it even requires a file upload which could've been avoided. – MSS Commented Sep 3, 2018 at 6:27
- Uploading a file has many more security considerations than plain text input. – Marty Commented Sep 3, 2018 at 11:00
1 Answer
Reset to default 18Here'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>