AppDividend
Latest Code Tutorials

Vuejs Form Validation Tutorial With Example From Scratch

990

Vuejs Form Validation Tutorial With Example From Scratch. We will use a VeeValidate library for the input form validation. A VeeValidate plugin for Vue.js that allows you to validate input fields, and display errors, naturally and compellingly.

Vuejs Form Validation

We can install this plugin via npm or a CDN. But we will do it later. First, generate a brand new Vue project.

Step 1: Install the Vue project.

Create one project folder and then open the terminal in that folder. We will install it using vue-cli. If you have not done yet, then please type the following command.

npm install -g @vue/cli

Now, create a new vue project and for that, hit the following command.

 vue create vueformvalidation

It generates scaffolding for us.

Step 2: Install the VeeValidate plugin.

Type the following command to install the VeeValidate plugin.

npm install vee-validate --save

Now, configure this plugin. Go to the src  >>  main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import VeeValidate from 'vee-validate'

Vue.use(VeeValidate);

Vue.config.productionTip = false

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

So, we have included the plugin, and now we can use this plugin anywhere in our application.

Step 3: Create a bootstrap input form.

<template>
  <div class="container">
      <div class="panel panel-primary">
        <div class="panel-heading">
           Add Network
        </div>
        <div class="panel-body">
          <form novalidate>
            <div class="form-group">
              <label>Network Name</label>
              <input type="text" name="name"/>
            </div>
            <div class="form-group">
              <label>Network Bandwidth</label>
              <input type="text" name="bandwidth"/>
            </div>
            <div>
              <button  class="btn btn-primary">Add</button>
            </div>
          </form>
        </div>
      </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      name: '',
      bandwidth: ''
    }
  },
  computed: {
  isComplete() {
      return this.name && this.bandwidth;
    }
  },
  methods: {
    validateBeforeSubmit() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          alert('From Submitted!');
          return;
        }
      });
    }
  }
}
</script>

It is an essential bootstrap form. Now we need to add validation to it.

Step 4: Add Validation to the input field.

All you need is to add a v-validate directive to an input you wish to validate.

<input type="text" v-validate="'required'"  :class="{ 'input form-control': true }" name="name"/>
<input type="text" v-validate="'required'" :class="{'input form-control': true }" name="bandwidth"/>

This is how you can add the v-validate directive to your input tag.

Related Posts
1 of 9

I have just added the required rule in our field. There are more than 20 rules for the input field.

Step 5: Display the validation message.

We need to display the errors to the users. Vee-validate plugin augments the Vue.js instance with a private validator object and a public errors data object.

The errors object exposes simple methods to help you render errors:

  • first('field')Fetches the first error message related to that field.
  • collect('field')Fetches all error messages related to that field. Alternatively, you can pass nothing, and it will return errors grouped by areas.
  • has('field') Checks if there are any errors related to that field.
  • all() Gets all error messages.
  • any()  checks if there are any errors.

We can display the message based on our errors object.

<p class="text-danger" v-if="errors.has('name')">{{ errors.first('name') }}</p>
<p class="text-danger" v-if="errors.has('bandwidth')">{{ errors.first('bandwidth') }}</p>

Now, we need to prevent the form from submitting, if the values are not filled or not comply with our validation rules.

 <form @submit.prevent="validateBeforeSubmit" novalidate>

So, we need to use submit event and call the function on it. We can define the function and add the logic to it.

methods: {
    validateBeforeSubmit() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          alert('From Submitted!');
          return;
        }
      });
    }
  }

If all the validation passes then alert will be prompted, otherwise, errors will be shown on the front page.

We need to disable the button if there is any error.

<button :disabled="errors.any()"  class="btn btn-primary">Add</button>

Our final code with the validation looks like this.

// HelloWorldComponent.vue

<template>
  <div class="container">
      <div class="panel panel-primary">
        <div class="panel-heading">
           Add Network
        </div>
        <div class="panel-body">
          <form @submit.prevent="validateBeforeSubmit" novalidate>
            <div :class="{'form-group': true, 'has-error': errors.has('name') }">
              <label>Network Name</label>
              <input type="text" v-validate="'required'"  :class="{ 'input form-control': true }" name="name"/>
              <p class="text-danger" v-if="errors.has('name')">{{ errors.first('name') }}</p>
            </div>
            <div :class="{'form-group': true, 'has-error': errors.has('bandwidth') }">
              <label>Network Bandwidth</label>
              <input type="text" v-validate="'required'" :class="{'input form-control': true }" name="bandwidth"/>
              <p class="text-danger" v-if="errors.has('bandwidth')">{{ errors.first('bandwidth') }}</p>
            </div>
            <div>
              <button :disabled="errors.any()"  class="btn btn-primary">Add</button>
            </div>
          </form>
        </div>
      </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      name: '',
      bandwidth: ''
    }
  },
  computed: {
  isComplete() {
      return this.name && this.bandwidth;
    }
  },
  methods: {
    validateBeforeSubmit() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          alert('From Submitted!');
          return;
        }
      });
    }
  }
}
</script>

 

VeeValidate Tutorial

Vuejs Form Validation Tutorial With Example From Scratch is over. I have put the code on Github.

Fork Me On Github

 

Leave A Reply

Your email address will not be published.