1

Hi I am trying to validate if a file input is not empty so I am doing this:

My HTML code:

<input accept="image/jpeg, image/png, image/gif" type="file" class="form-control" v-on:change="onFileChange">

I am doing the validation in the button:

<button 
     :disabled="I need to know what it'll be here ? !isDisabled : isDisabled"
     type="submit"
     class="btn btn-success btn-icon-split">
      <span class="icon text-white-50">
         <i class="fas fa-check"></i>
      </span>
     <span class="text">Guardar</span>
</button>

But I do not know how to do that because it does not have v-model and I do not know how to check if it's empty. How could I do that?

Thanks

3 Answers 3

5
<div id="app">
    <input type="file" @change="fileChange">
    <button :disabled="noFiles">Submit</button>
</div>

With the Composition API

const { createApp, ref } = Vue;

createApp({
    setup() {
        const noFiles = ref(true);
        const fileChange = (e) => noFiles.value = !e.target.files.length;

        return { noFiles, fileChange };
    },
}).mount('#app');

Without the Composition API

new Vue({
    el: '#app',
    
    data: () => ({
        noFiles: true,
    }),

    methods: {
        fileChange(event) {
            this.noFiles = !event.target.files.length;
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You need something like this:

data(){
   return{
      file: null,
   }
}

methods: {
   onFileChange(){
      this.file = event.target.files[0];
   }, 
}

and check in button submit method:

if(this.file !== null){
   //some code
}

Comments

1

Add a ref to the file input then inside the submit handler check this.$refs.file.files length :

 <input accept="image/jpeg, image/png, image/gif" ref="file"
    type="file" class="form-control" v-on:change="onFileChange">
  save(){
      console.log(this.$refs.file.files.length)
    }

LIVE EXAMPLE

6 Comments

Hi but when I use that it says [Vue warn]: Error in render: "TypeError: Cannot read property 'files' of undefined" :/ what could it be? I added ref="file" and I added this this.$refs.file.files.length to the submit button :disabled
are you using composition api?
i mean setup like in @MattDeacalion answer
No I am not using setup I just do this in a method onFileChange(e){ console.log(e.target.files[0]); this.file = e.target.files[0]; }, My thing is how I can add the validation disabled in the button
I did what you put but it says that it's undefined
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.