Using Joi plugin for validation in Hapi

In Hapi, you can validate incoming data using the Joi plugin. It’s object schema language and provides a perfect mechanism to validate JavaScript objects. This plugin comes from Hapi infrastructure, so you don’t need to install any additional packages. You can create your own validation schemas, multiple and conditional schemas.

Payload validation

For example, you have the next form on client:

The POST /form will receive the namemailmsg fields. We can assume that the server should validate the fields according to the following logic:

  • name – a string, minimum 3 characters, maximum 15 characters, required;
  • mail – a string, real email, required;
  • msg – a string, can be empty.

Let’s create a basic Hapi server with POST /form route and include Joi:

You can define a validation schema in options.validate object inside the route for payload data. In our case, it will be the following:

If client will send the wrong data, server will response the following:

Query validation

To validate query params, you need to pass your validation schema inside the options.validation.query property. For example, we send the size and page parameters to GET /orders endpoint. These parameters will be numeric and not negative. When the client don’t send them, server will set default values: size=20 and page=1. Our route will look like this:

Params validation

If we want to validate the params in route, we should put validation schema to options.validation.params property. For example, if you have the route GET /orders/{id}, you should allow pass only numeric values to id parameter. An example:

Headers validation

The validation of headers is possible using the options.validation.headers object. An example:

If headers will not pass validation, the client will get the following error:

Schema methods

There are many methods to validate data using Joi. Dates can be validated using the following methods:

  • min()
  • max()
  • less()
  • greater()
  • timestamp()
  • iso()

Some of methods to validate strings:

  • creditCard()
  • email()
  • ip()
  • uri()
  • hex()
  • base64()

About all of these methods to validate numbers, strings, objects, boolean and etc, you can read in official Hapi doc https://github.com/hapijs/joi/blob/v14.3.1/API.md.

If you liked this, please help spread the word by hitting the recommend button below. Thanks!