diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

File validation in vueJS with vee-validate

As we know, "v-model" does not work on an input that has a type of "file". So to validate a file is a little bit tricky.

For this validation, we will use vee-validate -> https://vee-validate.logaretm.com/v4/

To do this, you need to add a method that triggers the "on change" event on your input and to add on the "ValidationProvider" a ref.

import { ValidationProvider } from 'vee-validate/dist/vee-validate.full.esm'

<ValidationProvider ref="provider" rules="required">
 <input
 ref="file"
 type="file"
 @change="onFileAdd"
 />
</ValidationProvider>

Also you need to go and create the "onFileAdd" method , which will contain the following code:

export default {
 data() {
  return {
    fileData: '',
  }
 }

 methods: {
  async onFileAdd(e){
   const { valid } = await this.$refs.provider.validate(e)
   if (valid) {
    const file = this.$refs.file.files[0]
    this.fileData = file
   }
  }
 }
}

The "fileData" in the data object is the file that will be sent when the form is submitted.

Commit your changes. That's all.