All Projects → VitorLuizC → vue-form-container

VitorLuizC / vue-form-container

Licence: MIT license
👜 A Provider Component that encapsulate your forms and handle their states and validations.

Programming Languages

Vue
7211 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to vue-form-container

vue-validate-easy
你绝对没用过这么好用的vue表单验证插件。You never used such a good Vue form verification plug-in.
Stars: ✭ 12 (-47.83%)
Mutual labels:  vue-validator, vue-validate
vue-music
基于Laravel5.3+Vue2.0的网易云音乐的SPA应用
Stars: ✭ 85 (+269.57%)
Mutual labels:  vue-component
v-owl-carousel
🦉 VueJS wrapper for Owl Carousel
Stars: ✭ 46 (+100%)
Mutual labels:  vue-component
layui-vue
layui - vue(谐音:类 UI) 是 一 套 Vue 3.0 的 桌 面 端 组 件 库
Stars: ✭ 112 (+386.96%)
Mutual labels:  vue-component
vue-pattern-input
Use RegExp to limit input
Stars: ✭ 25 (+8.7%)
Mutual labels:  vue-component
vue-tiny-pagination
A Vue component for create a tiny pagination with Flexbox
Stars: ✭ 20 (-13.04%)
Mutual labels:  vue-component
vue-eva-input
A beautiful input component based on Eva Design System and Vue.
Stars: ✭ 17 (-26.09%)
Mutual labels:  vue-component
vue-money-button
An unofficial Vue.js component for MoneyButton.
Stars: ✭ 22 (-4.35%)
Mutual labels:  vue-component
vue-magnify
vue-magnify / vue放大镜组件
Stars: ✭ 14 (-39.13%)
Mutual labels:  vue-component
vue-telegram-login
Vue component for Telegram login
Stars: ✭ 73 (+217.39%)
Mutual labels:  vue-component
vue-ele-import
超简单、好用的 element-ui Excel 导入组件
Stars: ✭ 50 (+117.39%)
Mutual labels:  vue-component
vue-odometer
Vue.js(v2.x+) component wrap for Odometer.js
Stars: ✭ 63 (+173.91%)
Mutual labels:  vue-component
vue-dictaphone
🎙️ Vue.js dictaphone component to record audio from the user
Stars: ✭ 22 (-4.35%)
Mutual labels:  vue-component
vue-drag-zone
Drag Zone component for @vuejs
Stars: ✭ 127 (+452.17%)
Mutual labels:  vue-component
vue-g2
基于 Vue 和 AntV/G2 的可视化组件库 📈
Stars: ✭ 73 (+217.39%)
Mutual labels:  vue-component
vue-input-contenteditable
The same features you expect from `<input type="text">` but in a `contenteditable` Vue component
Stars: ✭ 19 (-17.39%)
Mutual labels:  vue-component
vue-circle-choice
A circle color choice and navigation with Vue.js
Stars: ✭ 20 (-13.04%)
Mutual labels:  vue-component
vue-github-activity
A Vue based github feed activity component.
Stars: ✭ 28 (+21.74%)
Mutual labels:  vue-component
vue-digital-transform
A vue component for better digital transform animation
Stars: ✭ 52 (+126.09%)
Mutual labels:  vue-component
vue-next-level-scroll
Bring your scroll game to the next level!
Stars: ✭ 49 (+113.04%)
Mutual labels:  vue-component

vue-form-container

min size min + zip size License FOSSA Status

A Provider Component that encapsulate your forms and handle their states and validations. Under the hood it uses valite, a light and concise validator engine that works on asynchrony. The idea of having a component handling the states and validations of the forms I took from formik and vue-final-form.

Installation

This library is published in the NPM registry and can be installed using any compatible package manager.

npm install --save vue-form-container

# Use the command below if you're using Yarn.
yarn add vue-form-container

Getting Started

Wrap your form, or wrapper element, with the FormContainer component passing the initial state of the fields and a scheme with the validations. Use slot-scope to receive the FormContainer scope with fields, errors, and so on.

<template>
  <form-container :initial="{ name: '' }" :schema="{
    name: [
      (name) => name.length > 0 || 'Name is required.'
    ]
  }">
    <div slot-scope="{ fields, errors }">
      <label>Name</label>
      <input v-model="fields.name" type="text" />
      <span>{{ errors.name }}</span>
    </div>

FormContainer is a renderless component, so it can receive just a single element as slot.

You can change the form field states and perform their validations using update functions or by changing the state of the fields object, which is a Proxy.

Due to platform limitations, fields (properties) need to be defined in schema or initial. If you don't want to initialize the value of a field, use undefined for it in initial or an empty list of validations in schema.

It is extremely important that the field exists on at least one of the objects.

<template>
  <form-container :initial="{ empty: undefined }">
  <!-- OR -->
  <form-container :schema="{ empty: [] }">

To use the FormContainer validations, fields and errors outside the template you should use a ref as in the example:

<template>
  <form-container ref="form" ... >
    <form ... @submit.prevent="onSubmit()">
      ...
      <button type="submit">Sign In</button>
    </form>
  </form-container>
</template>

<script>
  export default {
    methods: {
      async onSubmit () {
        // A FormContainer instance to handle fields, validate methods and other stuff.
        const form = this.$refs.form;

        await form.validateForm();
        if (!form.isValid)
          return;

        console.log('fields', form.fields);
      }
    }
  };
</script>

API

FormContainer props

Name Type Description
schema ValidatorSchema Schema of validators for form fields.
initial Object Initial state of form fields.

About ValidatorSchema type

ValidatorSchema is an object whose key is the name of the field and the value is a collection of validations. Validations are just functions that receive the value of the field and return true if it is valid and a string with the error message if it is invalid, these functions can also be asynchronous by returning a Promise that returns the same values (true or string with the error message).

type Validator = (value: any) => true | string | Promise<true | string>;

type ValidatorSchema = { [field: string]: Validator[]; };

...

const schema: ValidatorSchema = {
  name: [
    (name) => !!name.trim() || 'Name is required.',

    async (name) => {
      const isRepeated = await services.isRepeatedName(name);
      return !isRepeated || 'Name is repeated.';
    }
  ]
};

FormContainer properties and methods (also received by slot-scope)

Name Type Description
isValid boolean Indicates if form fields are valid.
isLoading boolean Indicates if there's a validation running.
errors MessageSchema Error scheme of form fields.
fields Proxy<{ [field: string]: any }> Proxy with form fields. It uses getters to get the state of the field and setters to update it.
update (field: string, value: any) => void Updates the state of the field using the value.
validateField (field: string) => Promise<void> Executes the schema validations for the field field.
validateForm () => Promise<void> Executes the validations on all fields specified in the schema.

About MessageSchema type

MessageSchema is a reflection of the scheme used to define the validations and contains the error messages (or null) for the fields.

type Message = string | null;

type MessageSchema = { [field: string]: Message; };

...

const errors: MessageSchema = {
  name: 'Use first and last name.',
  email: 'E-Mail is required.',
  phone: null, // No error message, because validators have returned true.
};

Example

<template>
  <form-container ref="form" :schema="schema" :initial="initial">
    <form slot-scope="{ fields, errors, submit }" @submit.prevent="onSubmit()">
      <fieldset>
        <label>Name</label>
        <input type="text" v-model="fields.name" />
        <span v-if="errors.name">{{ errors.name }}</span>
      </fieldset>

      <fieldset>
        <label>E-Mail</label>
        <input type="email" v-model="fields.email" />
        <span v-if="errors.name">{{ errors.email }}</span>
      </fieldset>

      <button type="submit">Sign Up</button>
    </form>
  </form-container>
</template>

<script>
  import FormContainer from 'vue-form-container';
  import * as services from './services';

  // FormContainer schema to validate fields.
  const schema = {
    name: [
      (name) => !!name.trim() || 'Name is required.'
    ],
    email: [
      (email) => !!email.trim() || 'E-Mail is required.',
      (email) => /^.+@.+\..+$/.test(email) || 'E-Mail is invalid.',
      async (email) => {
        const isRepeated = await services.isRepeatedEMail(email);
        return isRepeated || 'E-Mail is already registered.'
      }
    ]
  };

  export default {
    components: { FormContainer },
    data () {
      return {
        schema,

        // FormContainer fields initial state.
        initial: { name: '', email: '' }
      };
    },
    methods: {
      async onSubmit () {
        await this.$refs.form.validateForm();

        if (!this.$refs.form.isValid)
          return;

        console.log('submit fields', this.$refs.form.fields);
      }
    }
  };
</script>

License

Released under MIT License.

FOSSA Status

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].