Vue.js Form Validation example with VeeValidate

vuejs-form-validation-example-veelidate-feature-image

In this tutorial, we’re gonna make a Vuejs Form Validation example with VeeValidate.

Example Overview

Our form has 3 fields:
– Username: check existence
– Email: check existence, then check email format
– Password: check existence, then check if at least 6 characters

vue-form-validation-demo

Practice

Add VeeValidate to Vue Project

– with npm
npm install vee-validate

– with yarn
yarn add vee-validate

package.json after installation:


{
  "name": "vue-form-validation",
  ...
  "dependencies": {
    "vee-validate": "^2.1.1",
    "vue": "^2.5.17"
  },
  ...
}

Use VeeValidate

main.js


import Vue from "vue";
import App from "./App.vue";
import VeeValidate from "vee-validate";

Vue.use(VeeValidate);

new Vue({
  render: h => h(App),
}).$mount('#app');

Form Validation Component

We use v-validate directive for input tag we want to validate (make sure that it has a name attribute -> for error messages).

<input type="email" v-validate="'required|email'" name="email"/>
<div v-if="submitted && errors.has('email')">{{ errors.first('email') }}</div>

We pass to v-validate directive a string which contains a list of validation rules (separated by a pipe ‘|’).

In the example above:
required to indicate that the field is required
email to indicate that the field must be an email.

To display the error message, we use the errors.first() method:

<input type="email" v-validate="'required|email'" name="email"/>
<div v-if="submitted && errors.has('email')">{{ errors.first('email') }}</div>

We also use errors.has() and submitted bool variable for v-if directive.

components/FormValidation.vue

<template>
  <div class="container">
    <div class="row">
      <div class="col-sm-8 offset-sm-2">
        <div>
          <form @submit.prevent="handleSubmit">
            <div class="form-group">
              <label for="username">Username</label>
              <input type="text" v-model="user.username" v-validate="'required'" name="username" class="form-control" :class="{ 'is-invalid': submitted && errors.has('username') }" />
              <div v-if="submitted && errors.has('username')" class="invalid-feedback">{{ errors.first('username') }}</div>
            </div>
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" v-model="user.email" v-validate="'required|email'" name="email" class="form-control" :class="{ 'is-invalid': submitted && errors.has('email') }" />
              <div v-if="submitted && errors.has('email')" class="invalid-feedback">{{ errors.first('email') }}</div>
            </div>
            <div class="form-group">
              <label htmlFor="password">Password</label>
              <input type="password" v-model="user.password" v-validate="{ required: true, min: 6 }" name="password" class="form-control" :class="{ 'is-invalid': submitted && errors.has('password') }" />
              <div v-if="submitted && errors.has('password')" class="invalid-feedback">{{ errors.first('password') }}</div>
            </div>
            <div class="form-group">
              <button class="btn btn-primary">Register</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "app",
  data() {
    return {
      user: {
        firstName: "",
        lastName: "",
        email: "",
        password: ""
      },
      submitted: false
    };
  },
  methods: {
    /* eslint-disable no-console */
    handleSubmit() {
      this.submitted = true;
      this.$validator.validate().then(valid => {
        if (valid) {
          console.log("Successful!", JSON.stringify(this.user));
        } else {
          console.log("Fail to submit Form!");
        }
      });
    }
    /* eslint-enable no-console */
  }
};
</script>

App Component

App.vue

<template>
    <div id="app" class="container-fluid">
        <div class="site-info">
            <h1>grokonez</h1>
            <h3>Vue Form Validation example</h3>
        </div>
        <FormValidation />
    </div>
</template>

<script>
import FormValidation from "./components/FormValidation.vue";

export default {
  name: "app",
  components: {
    FormValidation
  }
};
</script>

<style>
.site-info {
  color: blue;
  margin-bottom: 20px;
}

.container-fluid {
  text-align: center;
}
</style>

Source Code

vue-form-validation



By grokonez | November 5, 2018.

Last updated on May 4, 2021.



Related Posts


Got Something To Say:

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

*