Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Vue Forms Tutorial - Capturing and Validating User Input

By Gary simon - Feb 10, 2018

Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example

Handling user input with Vue.js is fairly straight forward. With the help of the v-model directive and one of several vue validation plugins for form validation.

While the app we're building will only contain a single text element, we will temporarily take a look at a few other form elements so that you have a better understanding of handling form input fields with Vue.

Let's get started!

If you prefer watching a video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

The Vue V-Model Directive

When you need to capture user input, you can use the v-model directive on form inputs and textareas, which enables 2-way data binding. It's very simple to use.

Open up our /src/components/Skills.vue file and adjust the template section to include the following:

<template>
  <div class="container">

    <!-- Add these two lines: -->
    <input type="text" placeholder="Enter a skill you have.." v-model="skill">
    {{ skill }}

    <!-- Remaining HTML removed for brevity -->

Next, in the <script> section, add the referenced skill property in the data section:

  data() {
    return {
      skill: '',  // Add this line
      skills: [
          { "skill": "Vue.js" },
          { "skill": "Frontend Developer" }
      ]
    }
  },

While we're in this file, let's style the input button in the CSS section real quick. Add this ruleset:

  input {
    width: calc(100% - 40px);
    border: 0;
    padding: 20px;
    font-size: 1.3em;
    background-color: #323333;
    color: #687F7F;
  }

Save the file and start typing in the input field. You will notice that the interpolated skill property beneath the input field will demonstrate that we've captured the user input as the user types:

This doesn't really do much for us though, so let's capture the user input when a form is submitted.

Form Submission in Vue

Modify the template of our Skills.vue file to the following:

    <form @submit.prevent="addSkill">
      <input type="text" placeholder="Enter a skill you have.."  v-model="skill">
    </form>

Here, we're just wrapping our input with a form element. We use @submit.prevent, which submits the form and prevents a page reload, and bind it to a method called addSkill.

Let's define addSkill as a method in our component logic:

export default {
  name: 'Skills',
  data() {
    // Removed for brevity
  },

  // Add this section:
  methods : {
      addSkill(){
          this.skills.push({skill: this.skill});
          this.skill = '';
      }
  }
}

Here, all we're doing is defining a method called addSkill(), and when it's called, we push to the skills array defined in the data() section, and then we clear the input by resetting the skill property to an empty string.

Try entering a skill and hitting the enter key. It will add it to the list beneath the input field:

Handling Multiple User Inputs

While our form will only contain the current text input, we will add a checkbox just for the purpose of demonstration.

Modify the template as shown:

    <form @submit.prevent="addSkill">
      <input type="text" placeholder="Enter a skill you have.."  v-model="skill">

      <!-- Add this line -->
      <input type="checkbox" id="checkbox" v-model="checked">

    </form>

In the script section add:

    return {
      checked: false,   // Add this, it sets the checked property to false
      skill: '',

Then, update the addSkill() method:

      addSkill(){
          this.skills.push({skill: this.skill});
          this.skill = '';
          console.log('The checkbox value is: '+this.checked)  // Add this
      }

If you check the checkbox and enter a string in the input and hit the enter key, the console will show you that the checkbox was checked.

We don't need this checkbox, so backup from the last several steps to remove the checkbox and associated code.

Vue Form Validation

There are several Vue form validation packages that you can install via npm or yarn. A popular validation package is called VeeValidate.

VeeValidate is a powerful plugin with a lot of options, but we will use just a couple basic options to ensure that our text input validates correctly.

First, we will install it in the console with yarn:

> yarn add vee-validate

Next, we have to add it to our /src/main.js file:

import Vue from 'vue'
import App from './App.vue'

import VeeValidate from 'vee-validate';  // Add this
Vue.use(VeeValidate);  // Add this

// Other code removed for brevity

Great! Now we're ready to use it.

Next, in /src/components/Skills.vue, modify the template:

<input type="text" placeholder="Enter a skill you have.." v-model="skill" v-validate="'min:5'" name="skill">
<p class="alert" v-if="errors.has('skill')">{{ errors.first('skill') }}</p>

Here, we've added v-validate set to min:5 and we gave the input a name which is required for VeeValidate.

Next, we're adding a new p element with a v-if directive. This states that if the errors object that VeeValidate produces has an error for skill, show the error through interpolation.

Before we give this a go, let's add a quick CSS ruleset for .alert:

  .alert {
    background: #fdf2ce;
    font-weight: bold;
    display: inline-block;
    padding: 5px;
    margin-top: -20px;
  }

If you save this, and type fewer than 5 characters, you will see this:

Great. But one problem exists, it will still allow you to submit the form despite entering less than 5 characters.

We can fix that by modifying the addSkill() method:

      addSkill() {
        this.$validator.validateAll().then((result) => {
          if (result) {
            this.skills.push({skill: this.skill});
            this.skill = '';
          } else {
            console.log('Not valid');
          }
        })
      }

Now, if you try to hit enter with fewer than 5 characters, it will not submit. Simple!

VeeValidate offers a wide variety of options that we haven't touched on, so I suggest checking out their documentation for more examples based on your needs.

Conclusion

Remember, this tutorial is just a part of a crash course, so we can't get too in depth into any one topic. Hopefully, however, you did gain some solid fundamental-based understanding of forms in Vue!

Next Lesson: Vue Animation

Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example


Share this post




Say something about this awesome post!