Data Validation in JavaScript (Node.js) with Joi and Yup

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Data Validation in JavaScript (Node.js): Joi and Yup



In any web application, especially on Node.js, one of the key tasks is checking incoming data. Without validation, you risk database errors, vulnerabilities (SQL injections, XSS), or incorrect server behavior. In this article, we will look at two of the most popular validation libraries: Joi and Yup. You will learn how to install them, create schemas, and integrate them with Express.



Why is server-side validation necessary?

Client-side validation (HTML5 or JavaScript in the browser) is convenient, but it is easily bypassed. Therefore, server-side validation is mandatory. It ensures that:

  • Data types match expectations (string, number, array).
  • Required fields are not empty.
  • Data does not exceed allowed sizes.
  • Formats (email, URL, phone) are correct.


Joi Library

Joi is a powerful validator from the creators of Hapi.js. It supports complex schemas, custom error messages, and asynchronous checks.



Installation

npm install joi


Example schema for user registration

const Joi = require('joi');

const userSchema = Joi.object({ username: Joi.string() .alphanum() .min(3) .max(30) .required() .messages({ 'string.min': 'Username must be at least 3 characters', 'string.max': 'Username must not exceed 30 characters' }), email: Joi.string() .email({ tlds: { allow: false } }) .required(), password: Joi.string() .pattern(new RegExp('^[a-zA-Z0-9]{8,30}$')) .required(), birth_year: Joi.number() .integer() .min(1900) .max(2024)});

// Validationapp.post('/register', (req, res) => { const { error, value } = userSchema.validate(req.body, { abortEarly: false }); if (error) { return res.status(400).json({ status: 'error', message: error.details.map(d => d.message).join(', ') }); } res.json({ status: 'success', data: value });});


Advanced Joi features

  • Array validation: Joi.array().items(Joi.string())
  • Conditional rules: .when('role', { is: 'admin', then: Joi.required() })
  • Custom functions: .custom((value, helpers) => { ... })


Yup Library

Yup is a lightweight and intuitive library, popular in the React ecosystem (Formik). But it also works great on the server.



Installation

npm install yup


Example schema for login

const yup = require('yup');

const loginSchema = yup.object().shape({ email: yup.string() .email('Enter a valid email') .required('Email is required'), password: yup.string() .min(8, 'Password must be at least 8 characters') .max(50) .required('Password is required')});

// Middleware for Expressasync function validateLogin(req, res, next) { try { const validatedData = await loginSchema.validate(req.body, { abortEarly: false }); req.validatedData = validatedData; next(); } catch (err) { res.status(400).json({ status: 'error', errors: err.errors // array of error messages }); }}

app.post('/login', validateLogin, (req, res) => { res.json({ status: 'success', data: req.validatedData });});


Yup features

  • Asynchronous validation by default (returns a Promise).
  • Data transformation: .transform((value) => value.tr

Recommendations