An easy way to overwrite Joi, Celebrate and Express error messages

Harrison Kamau
The Andela Way
Published in
2 min readMar 27, 2019
Photo by Henri L. on Unsplash

What is Joi?

Joi is an object schema definition language and validator for JavaScript objects. It is a magical tool that allows you to create a set of rules and validate input data against them. How cool?

Its NPM package boasts of close to 3 Million weekly downloads! Presumably, it is by far the most used JavaScript schema validator, on the planet.

Joi in play

Joi in play.

In the personSchema above, name is a required field, but age isn’t. Joi differentiates two by calling required() function on the specific field. It supports many types such as number , boolean , object , binary among others. Their API reference is loaded with this and more information.

What’s more, it’s also possible to define request data that cannot appear together!

optional, yet ordered request data/params

Imagine, you have a POST /users/signup endpoint responsible for signing up a user and saving the data to a users collection on MongoDB. With Joi, you can validate the data being sent as part of the request, either on the request body, params or even query ! Watch!

Joi for Koa

koi-joi-router

Koa-joi-router from the maintainers of Koa.js comes in handy here.

Express with Joi.

Express also has its own share of glory with celebrate being the Joi middleware of choice.

express-joi

I believe that was a good introduction to Joi. Onto the business of the day!

Customizing error messages from Joi.

If you send the POST /users/signup above using a REST API client, for instance, Postman, without passing an email , you’re likely to get the following error message from Joi:

“child \”email\” fails because [\”email\” is required]”.

This makes sense to you as the developer, but a typical user might not fathom.

Little tweak :)

custom error message for Joi

I hope you are able to use knowledge obtained from this tutorial to make your REST API work the way you want it to.

P.S.

Since GraphQL internally supports schema and its validation, I have purposefully omitted it from the above statement :D

See you next time!

--

--