Validate HTML Forms with VeeValidate

VeeValidate is a plugin for #Vue that allows you to validate the HTML elements and show errors in an easy way, only adding the v-validate directive in the input and the validations that we need to be divided by a pipe.

VeeValidate has more than 20 validations by default, it also creates an errors objects where the references to all the validations that we have in our instance of Vue are stored.

The Errors object exposes methods to verify the status of validations, such as errors.first ('name') that obtains the first error message linked with the input name or errors.any () checks if it contains any pending validation and errors.has ( 'name') to verify if there are unsuccessful validations related to this field.

In my example, I have created a contact form where I validate the name, email, and message, and explain how VeeValidate works.

1- Add the reference of the scripts on our page.

<script src="https://unpkg.com/vue"> </ script> <script src="https://cdn.jsdelivr.net/npm/vee-validate@latest/dist/vee-validate.js"></ script> <script src="app.js"> </ script>

2- In our app.js specify Vue to use VeeValidate.

Vue.use (VeeValidate);

3- In our HTML use the v-validate directive in the elements that we need the validations. In this example I add the v-validate directive to the input name and the configuration that is a required field and at least 10 characters.

<div class="control"> <input type ="text" v-model="model.name" id="name" name="name" class="input" v-validate="'required' | min: 10"> </ div>

Using the has method of the errors object, it can determine if there is an error for the name to bring the specific error message of the name, in bonus to using the any method to disable the button if there is an error.

<p v-show="errors.has ('name')" class="help"> {{errors.first ('name')}} </ p> <div class="field"> <div class="control"> <button v-bind: disabled = "errors.any ()" class = "button is-primary"> {{title}} </ button> </ div> </ div> Feel free to see the official VeeValidate documentation http://vee-validate.logaretm.com