A useful form validator for VueJS framework

Last update: Nov 27, 2018

vuejs-easy-validator

A useful form validator for VueJS framework

Introduction

Suppose you work with VueJS framework.
Imagine a form with a lot of fields.
You need to write methods, check functions, computed state property... for each field.
For you : vuejs-easy-validator

Getting started

Import package in your app or in your SFC component :

// Works with Vue
import Vue from 'vue'
// Import (only class)
import Validator from 'vuejs-easy-validator'
// Import with 'map' functions
import { Validator, mapFieldStates, mapFieldCheckers } from 'vuejs-easy-validator'
// ...

Usage

Basic example

Use validator to check form

HTML template

">
<template>

    <form method="post" action="/articles" @submit="handleSubmit">

        <label for="articleTitle">Title :label>
        <input v-model="form.validator.fields.title.value" 
               id="articleTitle" 
               type="text" 
               name="title" 
               placeholder="Article title"/>

        <label for="articleContent">Content :label>
        <input v-model="form.validator.fields.content.value" 
               id="articleContent" 
               type="text" 
               name="content" 
               placeholder="Article content" />

        <input type="submit" name="submit" value="Save" />

    form>

template>

Javascript

import Validator from 'vuejs-easy-validator'
export default {
    data() {
        return {
            form: {
                // Empty object for validator
                validator: {},
                // Field definitions
                defs: [
                    // Article title
                    { name: 'title', value: '', verify: 'required|string|max:255' },
                    // Article content
                    { name: 'content', value: '', verify: 'string' }
                ]
            }
        }
    },
    methods: {
        handleSubmit: function (evt) {
            if ( this.form.validator.isValid() ) {
                console.log("Success!")
            }
            else {
                console.log("Ooops... an error has occurred!")
            }
            evt.preventDefault() // Prevent form from submitting
        }
    },
    created() {
        // You need to init form when component is 'created'
        this.form.validator = new Validator(this.form.defs)
    }
}

Example with 'map' functions

HTML template

Use 'map' functions to generate automatically computed properties and check methods

OK! The title is valid!

Article must have a title! (max: 255)

OK! The content is valid!

Article must have a content!

OK! The author ID is valid!

Article must have an author ID!

">
<template>

    <form @submit="handleSubmit">

        <label for="articleTitle">Title :label>
        <input v-model="form.validator.fields.title.value" 
               id="articleTitle" 
               type="text" 
               name="title" 
               placeholder="Article title"/>
        <p v-if="titleState">OK! The title is valid!p>
        <p v-else>Article must have a title! (max: 255)p>

        <label for="articleContent">Content :label>
        <input v-model="form.validator.fields.content.value" 
               id="articleContent" 
               type="text" 
               name="content" 
               placeholder="Article content" />
        <p v-if="titleState">OK! The content is valid!p>
        <p v-else>Article must have a content!p>

        <label for="articleAuthorId">Author ID :label>
        <input v-model="form.validator.fields.authorId.value" 
               id="articleAuthorId" 
               type="number" 
               name="authorId" 
               placeholder="Article author ID" />
        <p v-if="authorIdState">OK! The author ID is valid!p>
        <p v-else>Article must have an author ID!p>

        <input type="submit" name="submit" value="Save" />

    form>

template>

Javascript

titleState, contentState, authorIdState } ), }, methods: { // This function return check method for each given field. See below ...mapFieldCheckers( { ref: 'this.form.validator', fields: [ 'title', 'content', 'authorId' ] // -> titleChecker, contentChecker, authorIdChecker } ), handleSubmit: function (evt) { if ( this.form.validator.isValid() ) { axios.post( '/articles', this.validator.output ) .then( (response) => { console.log("Success!") } ) .catch( (error) => { console.log("Error!") } ) } else { console.log("Ooops... an error has occurred!") this.form.validator.errors.forEach( (fieldWithErrors) => { console.log("----") console.log("Error in : '" + fieldWithErrors.field.name + "' field ") fieldWithErrors.errors.forEach( (error) => { console.log("- for '" + error.prop + "', in '" + error.method + "' method : " + error.text ) } ) } ) } evt.preventDefault() // Prevent form from submitting } }, created() { // You need to init form when component is 'created' this.form.validator = new Validator(this.form.defs) } }">
import { Validator, mapFieldStates, mapFieldCheckers } from 'vuejs-easy-validator'  
export default {
    data() {
        return {
            form: {
                // Empty object for validator
                validator: {},
                // Field definitions
                defs: [
                    // Article title
                    { name: 'title', value: '', verify: 'required|string|max:255' },
                    // Article slug
                    { name: 'slug', value: '', varify: function(value) {
                        if ( /* value.match( new RegExp( "^([a-z0-9]|[a-z0-9]+-([a-z0-9]+-)*[a-z])$" ) ) */ ) { // preg match slug
                            return true 
                        }
                        else {
                            return false
                        }
                    } },
                    // Article content
                    { name: 'content', value: '', verify: 'required|string' },
                    // Article author ID
                    { name: 'authorId', value: null, verify: 'required|number|min:1' }
                ]
            }
        }
    },
    computed: {
        // This function return computed method for each given field. See below
        ...mapFieldStates( {
            ref: 'this.form.validator',
            fields: [ 'title', 'content', 'authorId' ] // -> titleState, contentState, authorIdState
        } ),
    },
    methods: {
        // This function return check method for each given field. See below
        ...mapFieldCheckers( {
            ref: 'this.form.validator',
            fields: [ 'title', 'content', 'authorId' ] // -> titleChecker, contentChecker, authorIdChecker
        } ),
        handleSubmit: function (evt) {
            if ( this.form.validator.isValid() ) {
                axios.post( '/articles', this.validator.output )
                     .then( (response) => {
                         console.log("Success!")
                     } )
                     .catch( (error) => {
                         console.log("Error!")
                     } )
            }
            else {
                console.log("Ooops... an error has occurred!")
                this.form.validator.errors.forEach( (fieldWithErrors) => {
                    console.log("----")
                    console.log("Error in : '" + fieldWithErrors.field.name + "' field ")
                    fieldWithErrors.errors.forEach( (error) => {
                        console.log("- for '" + error.prop + "', in '" + error.method + "' method : " + error.text )
                    } ) 
                } )
            }
            evt.preventDefault() // Prevent form from submitting
        }
    },
    created() {
        // You need to init form when component is 'created'
        this.form.validator = new Validator(this.form.defs)
    }
}

Enjoy! ... and sorry for my english ^^


GitHub

https://github.com/herveperchec/vuejs-easy-validator
You might also like...

RawModel.js plugin for Vue.js v2. Form validation has never been easier!

vue-rawmodel RawModel.js plugin for Vue.js v2. Form validation has never been easier! This plugin integrates RawModel.js framework into your Vue.js ap

Feb 3, 2022

Vue.js 2 form component that integrates jQuery Validation and Axios.

vue-vform Vue.js 2 form component that integrates jQuery Validation and Axios. Install Yarn yarn add vue-vform --dev NPM npm install vue-vform --save-

Jul 30, 2020

Form validation for Vue.js 2.2+

vue-form Form validation for Vue.js 2.2+ Install Available through npm as vue-form. import VueForm from 'vue-form'; // or var VueForm = require('vue-f

Apr 18, 2022

Vue form components with server-side validation in mind

Vue form components with server-side validation in mind

Vue form components with server side validation in mind About FormVuelar is a set of predefined vue form components which are designed to automaticall

Jun 12, 2022

A dependency-free Vue plugin for formatting and validating credit card form fields.

A dependency-free Vue plugin for formatting and validating credit card form fields.

Jun 24, 2022

Vue composition function for Form Validation

Form Validation for Vue 3 Vue composition function for Form Validation with async rules. 🌌 Written in TypeScript 🌊 Dynamic Form support 🍂 Light wei

May 11, 2022

Simple Vuex module to handle form fields and validations

Simple Vuex module to handle form fields and validations

vuex-module-validatable-state Simple Vuex module to handle form fields and validations. You can build a view model for your form, which runs valdation

Mar 31, 2022

Form Validation in Vue3 with TypeScript along with vuelidate for the validation

Vue3 with typescript Form Validation in Vue3 with vuelidate library Node Version Used: v14.17.3 Library Used for the validation: Vuelidate 2 Demo Link

May 21, 2022

Results of small 30 min online coding challenge + small polishing afterwards. Vue JS login form + Express JS login endpoint with CORS middleware and validation of request

Install dependencies: npm -i install Start FE: npm run serve ./frontend/src/main.js Start BE: node ./backend/controller/index.js ToDo: tests docker-co

Jan 14, 2022
Vue Laravel Validator This plugin handle laravel validation response and simple creating form and posting data

Vue Laravel Validator This plugin handle laravel validation response and simple creating form and posting data. #install npm i vue-laravel-validator -

May 29, 2021
A simple yet flexible validator library for vue.js

Simple Vue Validator Simple Vue validator is a lightweight yet flexible plugin for Vue.js 2.0 that allows you to validate input fields, and display er

Apr 11, 2022
Vue data validator - Easiness, simplicity, accurate

Overview This is a Vue data validator, trying to cover all needs and built on top of ES6 to achieve the best architecture. Demo You can view a demo an

Dec 8, 2021
Laravel frontend validator

An easy way to validate forms using backend logic.

Sep 8, 2021
Lite-validator.js - 轻量级的验证工具类,做纯数据验证,不操作相关DOM与事件注册,规则配置方便,简单易用

lite-validator.js 轻量级的验证工具类,做纯数据验证,不操作相关DOM与事件注册,规则配置方便,简单易用 依赖ES6的 Promise,如果需要低版本浏览器支持,请使用 dist/lite-validator.js 安装 npm install lite-validator --sa

Mar 26, 2021
Vue validator

vue-validator 3.8k before gzipped Install Note: the "vue-validator" on NPM refers to https://github.com/kazupon/vue-validator. $ npm install --save @j

Feb 22, 2018
Asynchronous form handling and validation for VueJS forms

Asynchronous form handling and validation for VueJS forms

Sep 24, 2019
Vee-validate: a template-based validation framework for Vue.js that allows you to validate inputs and display errors.

vee-validate is a template-based validation framework for Vue.js that allows you to validate inputs and display errors. Being template-based you only

Feb 28, 2020
✔ Template Based Validation Framework for Vue.js

vee-validate is a template-based validation framework for Vue.js that allows you to validate inputs and display errors.

Sep 1, 2019
✅ Form Validation for Vue.js
✅  Form Validation for Vue.js

vee-validate is a form validation library for Vue.js that allows you to validate inputs and build better form UIs in a familiar declarative style or u

Jul 4, 2022