Validate Forms in Vue JS

In this tutorial about ┬┐How to validate forms, fields or inputs in Vue?, we are going to make use of one of my npm packages, which is called @elpandev/laravel-validator and contains most of the rules that Laravel uses to validate forms.

Form in Vue

Before validating, we are going to create a form with the name and description fields, which will be found inside an html form and a prevent method called validate.

<template> <form @submit.prevent="validate()"> <input type="text" v-model="name"> <input type="text" v-model="description"> <button type="submit">validar</button> </form> </template>
Form Template

Additionally, we are going to create the validate method to validate the form fields.

<script lang="ts"> import Vue from 'vue' import Validator, { IMessages, IRules, IValues } from "@elpandev/laravel-validator"; export default Vue.extend({ data() { return { name: '', description: '' } }, methods: { validate() { const payload: IValues = { name: this.name, description: this.description, } const rules: IRules = { name: ['required'], description: ['required'] } const messages: IMessages = { name: { required: 'The field "name" is required' }, description: { required: 'The dield "description" is required' }, } const validator = new Validator(payload, rules, messages) console.log(validator.errors) } } }) </script>
Form Script

Form Validation

Now that we have our Vue component ready, we are going to leave the fields empty and validate our form, obtaining as a result 2 errors that match the "required" rule that we have added for each field.

{ description: ['The dield "description" is required'], name: ['The field "name" is required'], }
Form Errors

If you want to know more about the rules that this package contains, I recommend you review the Laravel validation rules, due to these rules are the same than this plugin contains but in typescript.