Validate input field in vue 3 app using vee-validate 4 CDN

Created at 24-Jan-2024 , By samar

In this tutorial, we'll explore a straightforward way to add input field validation to your Vue 3 application. We'll leverage the power of Vee-Validate 4 through a CDN, making the process simple and accessible for developers.

  • Example code to validate a input field in vue 3 using vee-validate 4

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Vue 3 with vee-validate 4 </title>
    
        <!-- Vue 3 CDN  -->
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
        <!-- veet-validate 4 CDN -->
        <script src="https://unpkg.com/vee-validate@4.12.4/dist/vee-validate.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@vee-validate/rules@4.12.4/dist/vee-validate-rules.min.js"></script>
    
    </head>
    <body>
    
    <div id="app">
        <div style="text-align: center; max-width: 400px; margin: 0 auto;">
            <div>
                <v-form @submit="onSubmit">
                    <v-field name="name" type="text" placeholder="Who are you" :rules="isRequired"></v-field>
                    <p><error-message name="name"></error-message></p>
                    </br>
                    <button>Submit</button>
                </v-form>
            </div>
        </div>
    </div>
    
    <script>
        
        const app = Vue.createApp({ 
    
            components: {
                VForm: VeeValidate.Form,
                VField: VeeValidate.Field,
                ErrorMessage: VeeValidate.ErrorMessage,
            },
    
            data: () => ({
                fromData: {
                    username : 'SAMAR',
                },
            }),
    
            methods: {
                isRequired(value) {
                    if (!value) { return 'this field is required';}
                    return true;
                },
    
                onSubmit(values) {
                    alert(JSON.stringify(values, null ,2));
                },
            }
        });
    
        app.mount('#app')
    </script>
    
    </body>
    </html>
    

    Simply create an index.html file and copy/paste above code in it and visit the URL to see the result.

  • Validating input fields in vue 3 app using vee-validate 4 and Yup CDN

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Vue 3 with Vueform-Multiselect </title>
    
        <!-- Vue 3 CDN  -->
        <!-- <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.15/vue.global.prod.min.js" integrity="sha512-Q4NoO9rQA70dtLz1DDYH/6paYbJG+Gu8qvGiUDelLKjR2NJH01uUaZd6jwJ/jlDr0WGaw9a+ShIhR3v98MspQg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
        <!-- veetvalidate -->
        <script src="https://unpkg.com/vee-validate@4.12.4/dist/vee-validate.js"></script>
    
        <!-- Yup Validation -->
        <script src="https://hardcore-mclean-89ac5f.netlify.app/yup.umd.js"></script>
    
        <!-- Vue-Multiselect 2.6.6 CDN -->
        <link rel="stylesheet" href="https://unpkg.com/@vueform/multiselect@2.6.6/themes/default.css">
        <script src="https://unpkg.com/@vueform/multiselect@2.6.6/dist/multiselect.global.js"></script>
    
    </head>
    <body>
    
    <div id="app">
        <div style="text-align: center; max-width: 400px; margin: 0px auto 300px;">
            <v-form @submit="onSubmit" @invalid-submit="onInvalidSubmit" :validation-schema="schema">
    
                
                <div class="single">
                    <h3 id="single">#1 - Single select</h3>
                    <Multiselect
                        v-model="single.value"
                        v-bind="single"
                    ></Multiselect>
                </div>  
                <div class="multiselectwrap" style="margin-bottom: 20px;">
                    <h3 id="multiselect">#2 - Multiselect</h3>
                    <v-field name="Movie" 
    				:value="multiselect.selectedOptions"
    				v-slot="{ errors, field }">
                        
                        <Multiselect v-model="multiselect.selectedOptions" v-bind="field" :mode="computedMode"  :options="multiselect.options[0].options">
                            <template v-slot:multiplelabel="{ values }">
                                <div class="multiselect-multiple-label" v-if="allSelected">All Selected</div>
                                <div class="multiselect-multiple-label" v-else >{{ values.length }} Lables selected </div>
                            </template>
                        </Multiselect>
                        <p style="color: red"><error-message  name="Movie"></error-message></p>
                    </v-field>
                </div>
                
                <div>
                    <label>
                        Email : 
                    </label>
                    <v-field name="Email" type="text"></v-field>
                    <p style="color: red"><error-message  name="Email"></error-message></p>
                </div>
    
                <div style="margin-bottom: 20px;">
                    <label>First Name : </label>
                    <v-field name="FirstName" type="text" ></v-field>
                    <p style="color: red"><error-message  name="FirstName"></error-message></p>
                </div>
    
                
                <div style="margin-bottom: 20px;">
                    <label>Last Name : </label>
                    <input type="text" name="LastName"  />
                    <p style="color: red"><error-message  name="LastName"></error-message></p>
                </div>
                
    
                <div>
                    <button>Submit</button>
                </div>
            </v-form>
        </div>
    </div>
    
    <script>
    
        const app = Vue.createApp({ 
            components: {
                Multiselect : VueformMultiselect,
                VForm: VeeValidate.Form,
                VField: VeeValidate.Field,
                ErrorMessage: VeeValidate.ErrorMessage,
            },
    
            data: () => ({
    
                schema :  Yup.object().shape({
                    Movie: Yup.string().required(),
                    Email: Yup.string().email().required(),
                    FirstName: Yup.string().required(),
                }),
                
                formData: {
                    firstName : 'samarjeet',
                    lastName : 'kumar'
                },
                single: {
                    value: 0,
                    options: ['Batman', 'Robin', 'Joker']
                },
                multiselect : {
                    mode: 'tags',
                    selectedMode: 'tags',
                    hideSelected : false,
                    searchable: true,
                    closeOnSelect: false,
                    groups : true,
                    canClear: false,
                    selectedOptions: [],
                    options: 
                    [
                        {
                            label: 'SELECT ALL',
                            options: ['Batman', 'Robin', 'Joker', 'The Dark Knight', 'Justice League']
                        },
                    ],
                    value: ['']
                },
            }),
    
            computed: {
                computedMode() {
                    return this.multiselect.selectedOptions.length <= 2 ? 'tags' : 'multiple';
                },
                allSelected() {
                    return this.multiselect.selectedOptions.length === this.multiselect.options[0].options.length;
                }
            },
    
            methods: {
                onSubmit(values, errors, results) {
                    formdata  = { ...values, ...this.formData };
                    console.log(formdata);
                    alert(JSON.stringify(formdata, null ,2));
                },
                onInvalidSubmit({ values, errors, results }) {
                    const firstErrorFieldName = Object.keys(errors)[0];
                    const el = document.querySelector(`[name="${firstErrorFieldName}"]`);
                    if (el) {
                        el.scrollIntoView();
                    }
                }
            }
        });
        app.mount('#app')
    </script>
    
    </body>
    </html>
    

    Simply create a yup.html file and copy/paste above code and visit URL in browser to see the validation of input field.

Back to code snippet queries related vuejs

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.