NODEJS SERIES

VineJS: Validation Library for NodeJs

Chikku George
Globant
Published in
6 min readNov 24, 2023

--

This article will go through the VineJS data validation library and utilize a NodeJS application to demonstrate how to use it.

What is VineJS?

VineJS is a data validation library that you may use in your NodeJS applications. Its codebase is not brand new, as it is an upgraded version of the previous AdonisJs validator codebase, making it a stand-alone library. It is solely designed for use with the NodeJs runtime in a backend environment. It cannot be run in a browser and is frequently used to validate the HTTP request body that your applications get.

Why do we need VineJS?

  • Many popular validation libraries are also available, such as Zod and Yup. However, VineJS stands out for its quickness. It’s faster than Zod or Yup. You can compare the results of validating a basic object with these libraries here. VineJS is 9 times faster than Zod.
  • VineJs will pre-compile your schemas, whereas Zod will not. When you define a schema and use it to execute validation, Zod re-parses the entire schema and performs validations. However, when you create your schema, VineJs compiles it into a Javascript function. This Javascript function has been highly optimized for performance. VineJs will do the validations using these pre-compiled schemas.
  • VineJS is only intended to be used for validating JSON payloads or form data that is requested via HTTP requests. Zod, on the other hand, is mostly used to validate all Javascript data types in your projects.
  • VineJS has more validation rules than Zod, including database-specific ones.
  • VineJS is relatively simple to extend. You can make custom rules and schema types.

How do we use VineJS for validation?

Let’s create a NodeJs application that will use VineJS as the validation library to validate an HTTP POST request. Set it up by following the steps below.

  1. Create a package.json file by running the command npm init -y
  2. Install the dependencies required to set up the server such as express, body-parser
npm i express body-parser

3. Install VineJS as follows.

npm i @vinejs/vine

4. Create an index.js file to start the server.

import express from "express";

const app = express();
const port = 8080;

app.listen(port, async () => {
console.log(`Server started at port ${port}`);
});

5. Import VineJS and add the schema validation as given below.

import express from "express";
import bodyParser from "body-parser";
import vine, { errors } from "@vinejs/vine";

const app = express();
const port = 8080;

const schema = vine.object({
name: vine.string(),
email: vine.string().email(),
password: vine.string().minLength(6).confirmed(),
});

app.use(bodyParser.json());

app.post("/", async (req, res) => {
const data = req.body;
try {
const validator = vine.compile(schema);
const output = await validator.validate(data);
res.status(200).send(output);
} catch (error) {
if (error instanceof errors.E_VALIDATION_ERROR) {
res.status(error.status).send(error.messages);
}
}

});

app.listen(port, async () => {
console.log(`Server started at port ${port}`);
});

The VineJS package is exclusive to ESM (ECMAScript Modules) and is not compatible with the CommonJS module system. The vine.object method defines the top-level object for the validation schema. vine.compile can pre-compile the given schema. VineJS will pre-compile your schema into an optimized JavaScript function. This optimized function can be later used for further validations. The validate method is used to carry out the validation. The validate method takes a data object as an argument and performs validation on the pre-compiled validator object.

If validation succeeds, the return value will be a new object with the validated properties. Consider the following data, which has no validation errors. It will return the input object with the validated properties.

Input data without any validation error

If validation fails, an exception will be thrown. Consider the data below, which has an invalid password field. It will throw an error with the appropriate message and validation rule.

Input data with an invalid password field

How to set up custom error message in VineJS

VineJS uses a message provider to manage the custom error messages. A message provider selects where to read the messages and how to handle validation errors. The message provider can be specified globally, per schema, or when the validate method is executed.

The SimpleMessageProvider takes two arguments. The first argument is the messages, which is an object of key-value pairs. The key can be the rule name or the field + rule combination, and the value is the error message. The second argument is an object of input fields. The input field name is substituted for the {{ field }} placeholder in error messages.

Configure globally

The simple message provider can be globally defined as follows. Such message providers are shared by all validator schemas in our application.

import vine, { SimpleMessagesProvider } from "@vinejs/vine";

const fields = {
name: "Name",
email: "Email",
password: "Password",
};

vine.messagesProvider = new SimpleMessagesProvider(
{
// Applicable for all fields
required: "The {{ field }} field is required",
string: "The value of {{ field }} field must be a string",
email: "The value is not a valid email address",

// Error message for the custom fields
"name.required": "Please enter name",
"email.required": "Please enter email",
"password.required": "Please enter password",
},
fields
);

Per schema level

We can define the default message provider at the schema level to ensure that it is available only for that particular schema. Once your schema has been pre-compiled, you can define the message provider on the optimized validator object that you receive.

import vine, { SimpleMessagesProvider } from "@vinejs/vine";

const fields = {
name: "Name",
email: "Email",
password: "Password",
};

const messagesProvider = new SimpleMessagesProvider(
{
// Applicable for all fields
required: "The {{ field }} field is required",
string: "The value of {{ field }} field must be a string",
email: "The value is not a valid email address",

// Error message for the custom fields
"name.required": "Please enter name",
"email.required": "Please enter email",
"password.required": "Please enter password",
},
fields
);

const schema = vine.object({
name: vine.string(),
email: vine.string().email(),
password: vine.string().minLength(6),
});

const validator = vine.compile(schema);
validator.messagesProvider = messagesProvider;

On validation call

During the validation call, the message provider can also be defined. By using the validate method, the data is validated against a schema. You have the option to share the message provider with the validator in the manner described below.

import vine, { SimpleMessagesProvider } from "@vinejs/vine";

const fields = {
name: "Name",
email: "Email",
password: "Password",
};

const messagesProvider = new SimpleMessagesProvider(
{
// Applicable for all fields
required: "The {{ field }} field is required",
string: "The value of {{ field }} field must be a string",
email: "The value is not a valid email address",

// Error message for the custom fields
"name.required": "Please enter name",
"email.required": "Please enter email",
"password.required": "Please enter password",
},
fields
);

const schema = vine.object({
name: vine.string(),
email: vine.string().email(),
password: vine.string().minLength(6),
});

const validator = vine.compile(schema);
validator.validate(data, { messagesProvider: messagesProvider });

Summary

We just demonstrated how to use the VineJS library to validate the HTTP request content in Node.js applications in this article. VineJS stands out amid other validation libraries, such as Yup and Zod. We have only examined a sample validation schema and the validation process in this post. You can go into greater detail on your own by referring here.

--

--

Chikku George
Globant

Software Engineer | ReactJS | NodeJS | Blockchain Enthusiast