- Tero Auralinna's web development blogAuralinna.blogTero Auralinna's blog about intriguing world of web development. Tweaking pixels since the '90s.

How to build a complete form with Vue.js

Published: 5/2/2018

Lately I have experimented with Vue.js JavaScript Framework. In this post I will show how to build an almost functional form with Vue.js. Almost functional means that the front end will be ready but actual data handling in the back end won't be implemented.

Forms are essential part of almost every web application so I wanted to see how to build a basic form with the following specs.


I set following specs for my form project.

  • Form contains different field types.
  • Textarea field must have a maximum length counter.
  • There must be an inline validation for form fields.
  • Summary of validation errors must be shown on submit if validation fails.
  • Data will be sent via Ajax on submit and loading indicator is visible until HTTP request is finished.
  • Server-side errors will be returned and handled in the same way as errors on a client-side.
  • Double-clicks must be prevented by disabling the submit button when sending form.
  • Thanks page will be shown after form is successfully submitted.


Vue project is generated with the Webpack template.

Project needs few dependencies for functionalities which are not part of the Vue.js core:

Project uses Bootstrap 4.1.0 library for the form HTML markup. is used to provide polyfills for older browsers.

This post focuses on the front end. Back end is handled by Mocky REST API. Mocky enables the one to mock HTTP responses to test REST APIs. Of course you could use any local mock server but I decided to use Mocky because it's also accessible from the GitHub page.

Getting started

You can download the whole project from my GitHub repository. Live demo is also available.

$ git clone

Setup project

Install dependencies

$ npm install

Run project

Serve dev version from http://localhost:8080

$ npm run dev

Show me the code!

App setup


Bootstrap is added from the CDN to simplify things a little bit.

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Vue.js Demo Form</title>
    <link rel="stylesheet" 
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <script src=""></script>


This file includes all translation strings that our app uses. For a bigger app I would use translation file per language. Even though this project doesn't have multiple languages it's easier to handle form validation errors with translation strings.

export default {
  en: {
    form: {
      firstName: "First name",
      lastName: "Last name",
      email: "Email",
      terms: "I accept the terms and conditions",
      type: "Select subscription type",
      additionalInfo: "Additional info",
      submitted: "The form is submitted!",
      sentInfo: "Here is the info you sent:",
      return: "Return to the form",
      submit: "Submit",
      submitting: "Submitting",
      charactersLeft: "You have {charCount} character left. | You have {charCount} characters left.",
      types: {
        free: "Free trial subscription",
        starter: "Starter subscription (50 € / month)",
        enterprise: "Enterprise subscription (250 € / month)"
    error: {
      invalidFields: "Following fields have an invalid or a missing value:",
      general: "An error happened during submit.",
      generalMessage: "Form sending failed due to technical problems. Try again later.",
      fieldRequired: "{field} is required.",
      fieldInvalid: "{field} is invalid or missing.",
      fieldMaxLength: "{field} maximum characters exceeded."


In the config file you can change the API endpoint. There is one for success and one for failure. With the failure response you can see how the back end responds when there are errors.

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  FORM_API_URL: '""', // Success
  //FORM_API_URL: '""', // Failure

Success response from

  "success": true,
  "errors": []

Failure response from

  "success": false,
  "errors": [
      "field": "firstName",
      "message": null
      "field": "lastName",
      "message": null
      "field": "email",
      "message": "Email is not valid email address."
      "field": "additionalInfo",
      "message": "Max. 1000 characters."


All dependencies and general configurations are inserted to the main.js file.

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Vuelidate from 'vuelidate';
import App from './App.vue'
import translations from "./resources/translations";


Vue.config.formApiUrl = process.env.FORM_API_URL;

const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: translations

new Vue({
  el: '#app',
  render: h => h(App)


App.vue is the container for the app. The form component is imported here.

  <div id="app" class="container">
    <div class="row justify-content-center">
      <div class="col-xs-12 col-sm-10 col-md-6">
        <h1 class="text-center">{{title}}</h1>

import Vue from 'vue';
import Form from './components/form/Form.vue';

export default {
  name: 'app',
  data () {
    return {
      title: 'Vue.js Demo Form'
  components: {
    appForm: Form

<style lang="scss">
  h1 {
    margin-bottom: 30px;

  #app {
    padding: 20px;

The form component

The form component is separated into several files: Form.scss, Form.js and Form.vue. The latter holds the template and requires SCSS and JS files.


pre {
    white-space: pre-line;

form {
    background: #efefef;
    padding: 2rem 2rem 1rem;


The Form.js contains all logic which controls the form.

import { required, email, maxLength } from 'vuelidate/lib/validators';
import axios from 'axios';
import Vue from 'vue';

export default {
  name: 'app-form',
  data() {
    return {
      isSubmitted: false,
      isError: false,
      errorHeader: 'error.invalidFields',
      errors: [],
      types: this.getTypes(),
      submitting: false,
      form: {
        firstName: '',
        lastName: '',
        email: '',
        terms: false,
        type: null,
        additionalInfo: ''
  methods: {
    submit() {
      if (!this.$v.$error) {
      } else {
    enableSubmitLoader() {
      this.submitting = true;
    disableSubmitLoader() {
      this.submitting = false;
    sendFormData() {
      this.enableSubmitLoader();, this.form).then(response => {
      }).catch(error => {
    submitSuccess(response) {
      if ( {
        this.isSubmitted = true;
        this.isError = false;
      } else {
        this.errorHeader = 'error.invalidFields';
        this.errors =;
        this.isError = true;
    submitError(error) {
      this.errorHeader = 'error.general';
      this.errors = [{'field': null, 'message': 'error.generalMessage'}];
      this.isError = true;
    validationError() {
      this.errorHeader = 'error.invalidFields';
      this.errors = this.getErrors();
      this.isError = true;
    isErrorField(field) {
      try {
        if (this.getValidationField(field).$error) {
          return true;
      } catch (error) {}

      return this.errors.some(el => el.field === field);
    getErrors() {
      let errors = [];
      for (const field of Object.keys(this.form)) {
        try {
          if (this.getValidationField(field).$error) {
            errors.push({'field': field, 'message': null});
        } catch (error) {}
      return errors;
    getFieldClasses(field) {
      return { 'is-invalid': this.isErrorField(field) }
    getCharactersLeft(field) {
      try {
        return this.getValidationField(field).$params.maxLength.max - this.form[field].length;
      } catch (error) {
        return 0;
    getTypes() {
      return [{
        value: 'free', 
        label: ''
      }, {
        value: 'starter', 
        label: 'form.types.starter'
      }, {
        value: 'enterprise', 
        label: 'form.types.enterprise'
    getValidationField(field) {
      if (this.$v.form[field]) {
        return this.$v.form[field];
      throw Error('No validation for field ' + field);
    onFieldBlur(field) {
      try {
        if (this.getValidationField(field).$error) {
          if (!this.errors.some(el => el.field === field)) {
            this.errors.push({'field': field, 'message': null});
        } else {
          this.errors = this.errors.filter(el => el.field !== field);
      } catch (error) {}
    reload() {
      window.location = '';
  validations: {
    form: {
      email: { required, email },
      firstName: { required },
      lastName: { required },
      type: { required },
      terms: { required },
      additionalInfo: { maxLength: maxLength(1000) }
  watch: {
    errors() {
      this.isError = this.errors.length > 0 ? true : false;


This is the main component which contains the HTML template, data bindings and includes JS and SCSS files.

    <form v-if="!isSubmitted" @submit.prevent="submit" novalidate>
      <div class="form-group">
        <label for="firstName">{{ $t('form.firstName') }} *</label>
        <input type="text" class="form-control" id="firstName" v-model.lazy.trim="form.firstName" @blur="onFieldBlur('firstName')" v-bind:class="getFieldClasses('firstName')">
        <div v-if="isErrorField('firstName')" class="invalid-feedback">{{ $t('error.fieldRequired', { field: $t('form.firstName') }) }}</div>
      <div class="form-group">
        <label for="lastName">{{ $t('form.lastName') }} *</label>
        <input type="text" class="form-control" id="lastName" v-model.lazy.trim="form.lastName" @blur="onFieldBlur('lastName')" v-bind:class="getFieldClasses('lastName')">
        <div v-if="isErrorField('lastName')" class="invalid-feedback">{{ $t('error.fieldRequired', { field: $t('form.lastName') }) }}</div>
      <div class="form-group">
        <label for="email">{{ $t('') }} *</label>
        <input type="email" class="form-control" id="email" v-model.lazy.trim="" @blur="onFieldBlur('email')" v-bind:class="getFieldClasses('email')">
        <div v-if="isErrorField('email')" class="invalid-feedback">{{ $t('error.fieldInvalid', { field: $t('') }) }}</div>
      <div class="form-group">
        <label for="type">{{ $t('form.type') }} *</label>
        <select id="type" class="form-control" v-model="form.type" @blur="onFieldBlur('type')" v-bind:class="getFieldClasses('type')">
            <option v-for="type in types" v-bind:key="type.value" v-bind:value="type.value">{{ $t(type.label) }}</option>
        <div v-if="isErrorField('type')" class="invalid-feedback">{{ $t('form.type') }}</div>
      <div class="form-group">
        <label for="additionalInfo">{{ $t('form.additionalInfo') }}</label>
        <small class="text-muted form-text">{{ $tc('form.charactersLeft', getCharactersLeft('additionalInfo'), { charCount: getCharactersLeft('additionalInfo') }) }}</small>
        <div v-if="isErrorField('additionalInfo')" class="invalid-feedback">{{ $t('error.fieldMaxLength', { field: $t('form.additionalInfo') }) }}</div>
      <div class="form-group">
        <div class="form-check">
          <input type="checkbox" class="form-check-input" id="terms" v-model.lazy.trim="form.terms" @change="onFieldBlur('terms')" v-bind:class="getFieldClasses('terms')">
          <label class="form-check-label" for="terms">{{ $t('form.terms') }} *</label>
      <div class="alert alert-danger" v-if="isError">
        <p class="mb-0">
          <strong>{{ $t(errorHeader) }}</strong>
        <ul class="mb-0 pl-3" v-if="errors.length > 0">
          <li v-for="error in errors" v-bind:key="error.field">
            <span v-if="error.field">{{ $t('form.'+error.field) }}<span v-if="error.message">: {{ $t(error.message) }}</span></span>
            <span v-else-if="error.message">{{ $t(error.message) }}</span>
      <div class="form-group">
        <button type="submit" class="btn btn-primary" :disabled="submitting">
          <span v-if="submitting">{{ $t('form.submitting' ) }} <img src="../../assets/loader.svg" /></span>
          <span v-else>{{ $t('form.submit' ) }}</span>
    <div v-else>
      <div class="alert alert-success">
        <strong>{{ $t('form.submitted' ) }}</strong>
      <div class="alert alert-info">
        <p><strong>{{ $t('form.sentInfo' ) }}</strong></p>
      <p class="text-center">
        <a href="#" class="btn btn-secondary" @click.prevent="reload()">{{ $t('form.return' ) }}</a>

<script src="./Form.js"></script>
<style src="./Form.scss" lang="scss" scoped></style>

Further development ideas

For a real project I would consider refactoring common code from the Form.js into reusable services. I also would create a component per field type to avoid code duplication and for reusing fields in other forms. Another thing which tempts me is to create a model which represents the whole form. This model would include properties per form field like type, label, validation rules etc. Then forms could be generated dynamically based on the form model. Well this might be a topic for an upcoming blog post.

Be the first commenter?

Latest CodePens

I am an experienced web developer with an eye for solid UI/UX design. I have specialized in front-end development, responsive web design, design systems, modern web frameworks, and content management systems. I also have experience in mobile apps development and back-end coding with PHP, Node.js, and Java. So I have a full stackish background, but I'm enjoying most building robust and beautiful front-ends with performance, accessibility, and testability in mind.

© Tero Auralinna

Auralinna.fiSunset with Bubbles: Travel and Photography Blog

The icon "ellipsis" is provided by