How to Validate Form in Vue 3 with VeeValidate

Last Updated on by in Vue JS
Why do we validate form data in Vue? There is a primary purpose: We want to receive the correct data in the right format.In this tutorial, we learn how to create an HTML form in Vue, validate the form component using the VeeValidate plugin and Template-driven approach.

The template-driven approach is nothing but the simple way which allows you to validate your forms by combining attributes to inputs.

Create Vue 3 Project

Vue development is not possible without the help of VUE CLI tool; here is the command that can help you install the needed Vue CLI.

npm install -g @vue/cli

You are now ready to create a new vue app using the following command.

vue create vue-3-form-validation-example

Ensure that you choose [Vue 3] from the given list:

? Please pick a preset: (Use arrow keys)
> Default ([Vue 3] babel, eslint) 
  Default ([Vue 2] babel, eslint) 
  Manually select features 

Enter into the project directory.

cd -3-form-validation-example

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Vue multi word error

To remove multi-word error warning, add the following code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

Install VeeValidate

To install vee-validate package, run either of the commands among Yarn or NPM package manager.

npm install vee-validate  --legacy-peer-deps

Adding Bootstrap in Vue

Adding Bootstrap 5 in the Vue application is easy. Head over to public/index.html, in the head section add the Bootstrap CDN link.

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>

    <!-- Bootstrap Goes Here -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Create Form with Bootstrap in Vue

In the components/ folder, crate the VeeInput.vue file and add the given code.

<template>
  <input v-model="value" :type="type || 'text'" />
  <div class="text-danger">{{ errorMessage }}</div>
</template>

<script setup>
import { useField } from 'vee-validate';

const props = defineProps({
  name: String,
  type: String,
});

// The `name` is returned in a function because we want to make sure it stays reactive
// If the name changes you want `useField` to be able to pick it up
const { value, errorMessage } = useField(() => props.name);
</script>

Vue Form Validation with VeeValidate

Here, prevent method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

Initially, we are showing the Validation messages when the user clicks on the submit button.

Add the entire given code in the App.vue file:

<template>
  <div class="container mt-3">
    <form @submit="onSubmit">
      <div class="mb-3">
        <VeeInput name="firstName" class="form-control" />
      </div>
      <div class="mb-3">
        <VeeInput name="lastName" class="form-control" />
      </div>
      <div class="mb-3">
        <VeeInput name="email" type="email" class="form-control" />
      </div>
      <div class="mb-3">
        <VeeInput name="password" type="password" class="form-control" />
      </div>
      <div class="mb-3">
        <VeeInput name="passwordConfirm" type="password" class="form-control" />
      </div>
      <div>
        <button class="btn btn-primary">Submit</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { useForm } from 'vee-validate';
import * as yup from 'yup';
import VeeInput from './components/VeeInput.vue';

const { handleSubmit } = useForm({
  validationSchema: yup.object({
    firstName: yup.string().required(),
    lastName: yup.string().required(),
    email: yup.string().required().email(),
    password: yup.string().required().min(6),
    passwordConfirm: yup
      .string()
      .required()
      .min(6)
      .oneOf([yup.ref('password')]),
  }),
});

const onSubmit = handleSubmit(values => {
  alert(JSON.stringify(values, null, 2));
});
</script>

Here is the final main.js file:

import { createApp } from "vue";
import App from "./App.vue";

createApp(App).mount("#app");

Here is the final command that you have to execute to run the app’s development server:

npm run serve

How to Validate Form in Vue 3 with VeeValidate

Conclusion

Form validation is essential to protect forms by sending abusive emails by malicious users. Incorrect submission of form data may lead to deteriorate the functionalities and features of application.

Non validated forms may invite hackers to attacks using header injections, cross-site scripting, and SQL injections methods.

We learned to build a simple user registration form with: input fields such as name, email, mobile number, city, password, confirm password, and hobbies.

In this Vue form validation example, every field is a required field. We have email validation and password confirmation validation applied to the input fields.

To add the styling, we used a bootstrap-vue package, which is an alternative to Bootstrap for the Vue environment.

We just learned to create Forms in Vue and how to add validation using vee-validate plugin. It makes validating HTML inputs and Vue components super easy.