Validate HTTP Parameters & Body in Express

Express·2 min read·Jan 1, 2025

The second and probably most important part of the data handling process after parsing is called validation, as parsing alone is not enough to guarantee that the data sent by a user or another application respects the API contract.

In this context, validation refers to the process of ensuring the accuracy of the parsed data by matching its value, type, and format against a predefined model.

Get started with Joi

Joi is a JavaScript library used for validating objects.

$ npm install --save joi

The validation of an object with Joi is a two step process:

  1. First, we need to construct the schema of this object using types and constraints.
  2. Second, we need to validate this schema against an arbitrary value, which in this case will be the parsed message body of an incoming request.

Create a validation schema

In Joi, a schema refers to a set of rules that define the structure, types, and constraints that an object must adhere to in order to be considered valid.

To create a schema, we can use the top-level object() method exported by the joi module that takes as argument an object:

const Joi = require('joi');const schema = Joi.object({  property: Joi.type().constraint()});

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.