DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Originally published at webcraft-notes.com

Vue.js Form Validation: Vee-validate with simple words

Vee-validate with simple words

Check this post in my web notes!

Certain elements, such as forms and inputs, are ubiquitous in web application development. However, ensuring the accuracy and validity of user-provided data is paramount for the smooth functioning of these applications. That's where form validation comes into play. It allows developers to control the type of data accepted from users and provide informative feedback on the input correctness.

Previously, we discussed the possibility of crafting custom validators to suit our needs. In this article, we delve deeper into the topic by exploring vee-validate, a widely-used library for form validation in Vue.js. Vee-validate offers an extensive set of predefined validation rules, simplifying the process of implementing validation logic. Moreover, it empowers developers with the flexibility to customize existing rules or create new ones to accommodate project-specific requirements. Join us as we uncover the capabilities of vee-validate and learn how to leverage its features to enhance the validation process in Vue.js applications.

Here's a quick outline of what we'll be talking about in this article:

1. Prepare a new Vue.js project with Vee-Validate and a Simple Form:

  • Start by setting up a new Vue.js project and installing Vee-Validate.
  • Create a simple form with basic input fields to demonstrate validation.

2. Global Validators and Custom Rules:

  • Explore the concept of global validators provided by Vee-Validate.
  • Define custom validation rules tailored to your specific project requirements.
  • Introduce the @vee-validate/rules package and its significance in extending Vee-Validate's validation capabilities.

3. Field and Form-level Validation:

  • Dive into the distinction between field-level and form-level validation.
  • Demonstrate how to implement validation rules at the field level, ensuring data integrity for individual inputs.

Okay, we have much work to do and I'm offering you to start from the beginning, create a new project, and prepare Vee-Validate for use.

1. Prepare a new Vue.js project with Vee-Validate and a Simple Form

First, you need to be sure that you have installed Node.js and the Node Package Manager. You can find all versions on the Node.js website here.

We will create a Vue Application by using official documentation recommendations. Let's create a new folder and call it "vee-validate" and then open this folder with a code editor, in my case I will use VS Code.

In the terminal, we will add a command: npm create vue.

Then we will have to answer a few questions like: "Project name" - I will set "." so that my project name will be the same as the folder name; "Package name" - "vee-validate", you can write anything you want; on the next questions, I'll choose "no" everywhere.

Press Enter and then use the command: "npm i" to install all packages.

Next, we need to install "Vee-Validate" We will use instructions from its website. Simply run the npm command: " npm i vee-validate @vee-validate/rules --save" and wait until this dependencies are installed.

Then, remove all components and clean the App.vue file. Now we can add a simple form for our test purpose.

I will use one of the available forms on UIVerse html/css component library.

registration form

Great, all set and we can move to the second part, and start working with validation.

2. Global Validators and Custom Rules

Okay, we have a form and now we need to add validation to each field. There could be different rules for the different form fields so let's create a separate file where we will set those rules. Create a validation folder in our project with a validator.js file.

Import defineRule function from a vee-validate library. That is all we need to create our own rules.

We can start from the most popular rules like required, minimal length, email...

We will use the defineRule function, pass the rule name as the first parameter, and a callback function as the second one, that function will accept values, validate them, and return a result.

defineRule('required', value => {
    if (!value || !value.length) {
        return 'This field is required';
    }
    return true;
});

defineRule('minLength', (value, [limit]) => {
    if (!value || !value.length) {
        return true;
    }
    if (value.length < limit) {
        return `This field must be at least ${limit} characters`;
    }
    return true;
});
Enter fullscreen mode Exit fullscreen mode

Great, we have our first custom rules set and now we can import those rules to our vue js components and use them in forms or fields.

Also, we can use predefined rules from the @vee-validate/rules package, for that we can import them into our validator.js file and use them the same way as with our custom rules.

import { defineRule } from 'vee-validate';
import { required, min } from '@vee-validate/rules';

defineRule('required', required);
defineRule('min', min);
Enter fullscreen mode Exit fullscreen mode

That's much simpler, right? Yes but unfortunately he @vee-validate/rules package contains not all use cases that we might want.

Alright, after we clarified the way we can implement and define custom rules we can move on and start using those rules.

3. Field and Form-level Validation

We will open App.vue component with our form and start modifying it.

  • import Form, Field, and ErrorMessage components from the "vee-validate" library;

The "Form" component - provides declarative validation for form inputs based on defined validation rules.

The "Field" component - facilitates easy integration of input validation logic into forms by automatically handling input binding, validation, and error message rendering.

The "ErrorMessage" component - is used for displaying validation error messages associated with form fields.

  • change form with imported Form component and add "as" directive that will replace Form component with set HTML tag;

  • change inputs with imported Field component and add "as" directive that will replace Field component with a set HTML tag, in our case input;

  • add "rules" directive where will be defined rules that will be used to check input value;

  • add ErrorMessage component into the place where we want to show the error;

<Form as="form" class="form">
      <label>
          <Field as="input"
            placeholder="" 
            type="email" 
            class="input" 
            name="email"
            :rules="{ required: true, email: true }" />
          <span>Email</span>
      </label>
      <ErrorMessage name="email" />
</Form>
Enter fullscreen mode Exit fullscreen mode

Great, let's start our project and try to pass data into our updated email field.

register form validation

We have considered only the basics of work with vee-validate, the library has a rich functionality that you should consider if possible.In conclusion, mastering form validation is essential for creating user-friendly and error-free web applications. With Vee-Validate in Vue.js, developers have a powerful tool at their disposal to ensure data accuracy and enhance user experience. By following the steps outlined in this article, developers can confidently set up validation rules, customize them as needed, and implement validation logic seamlessly into their Vue.js projects.

Top comments (0)