Prevent submitting a form if at least one file is not selected

I am using Vue.js and Axios. I have two inputs on my html page for … Read more Prevent submitting a form if at least one file is not selected

I am using Vue.js and Axios.

I have two inputs on my html page for selecting an image. There is also a form. The two inputs and the form are separate and independent.

When I select an image, the image is automatically uploaded to the server.

The challenge is how to make it impossible to submit the form until at least one image is selected?

Tell me how to do this?

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Add Item</title>
        <script src="https://unpkg.com/[email protected]"></script>
        <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    </head>
    <body>

    <div id="app">

        <form name="addItem" method="post" action="/user/addItem">
            <label for="name">name</label>
            <input type="text" id="name">
            <button type="submit" id="submit">Save Item</button>
        </form>



        <form @submit.prevent enctype="multipart/form-data">
            <input type="file" ref="file1" @change="selectFile1">
        </form>

        <form @submit.prevent enctype="multipart/form-data">
            <input type="file" ref="file2" @change="selectFile2">
        </form>



    </div>


    <script>

        const addProduct = {

            name: "addProduct",

            data() {
                return{
                    file1: "",
                    image1:"",

                    file2: "",
                    image2: "",
                }
            },

            methods:{

                async selectFile1(){
                    const formData = new FormData();
                    this.file1 = this.$refs.file1.files[0];
                    formData.append('file', this.file1);
                    await axios.post('/user/uploadImage', formData)
                },

                async selectFile2(){
                    const formData = new FormData();
                    this.file2 = this.$refs.file2.files[0];
                    formData.append('file', this.file2);
                    await axios.post('/user/uploadImage', formData)
                }

            }
        }

        Vue.createApp(addProduct).mount('#app')
    </script>


    </body>
    </html>

Source: Vue – Stack Overflow


Categories: NewsTags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *