Skip to content

Instantly share code, notes, and snippets.

@bryandidur
Last active September 16, 2019 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryandidur/079ac3a2038cdeeb9ad785b1194f44f6 to your computer and use it in GitHub Desktop.
Save bryandidur/079ac3a2038cdeeb9ad785b1194f44f6 to your computer and use it in GitHub Desktop.
File input validation Vue component
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Client LAB</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="container">
            <div class="row" style="margin: 25px 0;">
                <div class="col-md-4 col-md-offset-4">
                    <file-input classes="form-control" accept=".jpg,.png,.pdf" maxsize="2" v-model="form.files"></file-input>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <button class="btn btn-primary" @click="handleClick">Submit</button>
                </div>
            </div>
        </div>
    </div>

    <script>
    Vue.component('file-input', {
        template: `
            <input type="file" :class="classes" :accept="accept" @change="handle">
        `,
        props: {
            classes: {
                type: String,
                default: '',
            },
            accept: {
                type: String,
                default: '.jpg,.png',
            },
            maxsize: {
                type: String,
                default: '4',
            },
        },
        data() {
            return {
                size: Number(this.maxsize) * 1000000,
            };
        },
        methods: {
            handle(event) {
                const { files } = event.target;

                for (let i = 0; i < files.length; i += 1) {
                    if (files[i].size > this.size) {
                        event.target.value = '';
                        this.$emit('input', []);
                        return;
                    }
                }

                this.$emit('input', event.target.files);
            },
        },
    });

    const App = new Vue({
        el: '#app',
        data() {
            return {
                form: {
                    files: [],
                },
            };
        },
        methods: {
            handleClick() {
                console.log('CLICK', this.form.files);
            },
        },
    });
    </script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment