Categories
JavaScript Vue

Adding Form Validation with vue-form-generator

Spread the love

Creating forms with validation can be a pain in a Vue.js project.

Therefore, solutions exists to let us create forms easily.

One of them if the vue-form-generator package.

To use it, we install the package by running:

npm install vue-form-generator

Then we can use it by including the library in our app:

main.js

import Vue from "vue";
import App from "./App.vue";
import VueFormGenerator from "vue-form-generator";
import "vue-form-generator/dist/vfg.css";

Vue.use(VueFormGenerator);
Vue.config.productionTip = false;

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

We include the CSS file that comes with the package.

Also, we call Vue.use with the package name to include the package.

Then we in App.vue, we write:

<template>
  <div id="app">
    <vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
    <p>{{model}}</p>
  </div>
</template>

<script>
import VueFormGenerator from "vue-form-generator";
VueFormGenerator.validators.email = value => {
  if (!/\S+@\S+\.\S+/.test(value)) {
    return ["invalid email"];
  } else {
    return [];
  }
};

export default {
  name: "App",
  data() {
    return {
      model: {
        id: 1,
        name: "jane smith",
        skills: ["Javascript"],
        email: "janesmith@example.com",
        status: true
      },
      schema: {
        fields: [
          {
            type: "input",
            inputType: "text",
            label: "ID ",
            model: "id",
            readonly: true,
            disabled: true
          },
          {
            type: "input",
            inputType: "text",
            label: "Name",
            model: "name",
            placeholder: "name",
            featured: true,
            required: true
          },
          {
            type: "select",
            label: "Skills",
            model: "skills",
            values: ["Javascript", "VueJS", "CSS3", "HTML5"]
          },
          {
            type: "input",
            inputType: "email",
            label: "E-mail",
            model: "email",
            placeholder: "e-mail address",
            validator: VueFormGenerator.validators.email
          },
          {
            type: "checkbox",
            label: "Status",
            model: "status",
            default: true
          }
        ]
      },
      formOptions: {
        validateAfterLoad: true,
        validateAfterChanged: true,
        validateAsync: true
      }
    };
  }
};
</script>

We import the vue-form-generator package’s VueFormGenerator component, then we add our own validator function by writing:

VueFormGenerator.validators.email = value => {
  if (!/\S+@\S+\.\S+/.test(value)) {
    return ["invalid email"];
  } else {
    return [];
  }
};

We just check if what we entered matched the email format and return an array with our form validation error message if it doesn’t.

Otherwise, we return an empty array, which indicates that what we entered is valid.

Then in our data method, we return:

{
  model: {
    id: 1,
    name: "jane smith",
    skills: ["Javascript"],
    email: "janesmith@example.com",
    status: true
  },
  schema: {
    fields: [{
        type: "input",
        inputType: "text",
        label: "ID ",
        model: "id",
        readonly: true,
        disabled: true
      },
      {
        type: "input",
        inputType: "text",
        label: "Name",
        model: "name",
        placeholder: "name",
        featured: true,
        required: true
      },
      {
        type: "select",
        label: "Skills",
        model: "skills",
        values: ["Javascript", "VueJS", "CSS3", "HTML5"]
      },
      {
        type: "input",
        inputType: "email",
        label: "E-mail",
        model: "email",
        placeholder: "e-mail address",
        validator: VueFormGenerator.validators.email
      },
      {
        type: "checkbox",
        label: "Status",
        model: "status",
        default: true
      }
    ]
  },
  formOptions: {
    validateAfterLoad: true,
    validateAfterChanged: true,
    validateAsync: true
  }
};

We use the validator function we created as the value of the validator property.

The schema property is used to define the form field behavior with various properties.

The model property will be the value that’s populated when we enter something into the form.

formOptions includes form options for changing validation behavior. We specified that we want to validate after the form is loaded or changed, and do both asynchronously

In the template, we have the vue-form-generator component, with the schema and model returned in the object returned by the data method.

In the end, we get:

https://thewebdev.info/wp-content/uploads/2020/05/form.png

It’s easy to create a form with validation with the vue-form-generator package.

All we have to do is to pass in some objects as props into the vue-form-generator component including the models and form field options and then we’re set.

Leave a Reply

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