Vue vuelidate not working file type input

9k views Asked by At

I'm used validate for vue js form validation.(https://vuelidate.js.org/#getting-started)

It's good to work with my all scenarios.

But it's not working in form upload file validation.

Because file type input can't set v-model attribute and I have the below error in v-model attribute adding time.

'v-model' directives don't support 'file' input type.

So that value not changed. My code sample below.

<input type="file" id="input-file-now" class="dropify" multiple accept="image/*"
  @change="model.file = eDatas.target.files" v-bind:class="{'is-invalid': $v.model.file.$error}">
<div v-if="$v.model.file.$error" class="invalid-feedback">
  Select Image
</div>


data () {
  return {
    model: {}
  }
},
validations: {
  model: {
    title: { required },
    file: {
      required: requiredIf(function (nestedModel) {
        return !this.model.file || this.model.file.length == 0;
      })
    }
  }
},

I try to requiredIf but that also not working. If you know this solution. Kindly share it with me.

2

There are 2 answers

0
Jai Kumaresh On BEST ANSWER

I got my mistake. And requiredIf is the solution to form file type input validation.

My mistakes are model value init file: [] & requiredIf condition.

data () {
  return {
    model: {
      file: [] // New changes
    }
  }
},
validations: {
  model: {
    title: { required },
    file: {
      required: requiredIf(function (nestedModel) {
        return this.model.file.length == 0; // New changes
      })
    }
  }
}

The validate(https://vuelidate.js.org/#getting-started) is very useful in vue js

0
Nand On

Here's the code that worked fine in my case...

Vue template

<input type="file" :class="{ 'is-invalid': $v.imageFile.$error }" 
@change="imageFileChanged($event)" accept="image/png, image/jpeg" />

Script code:

export default {
  data() {
    return {
      imageFile: ""
    }
  },
  validations: {
    imageFile: {
      file_size_validation
    }
  },
  methods: {
    imageFileChanged(event) {
      var files = event.target.files || event.dataTransfer.files;
      if (!files.length) {
        return;
      }
      this.imageFile = files[0];
    },
  }
}

The validation:

const file_size_validation = (value, vm) =>  {
  if (!value) {
    return true;
  }
  let file = value;  return (file.size < 2097152);
}