Marco Chavez

Marco Chavez

Hapi Joi - request validation

Yes.. I know Joi is no longer a part of Hapi but what a nice name that was!

In case the title didn’t give it away, today I’ve been working handfuls with request validation. The thin layer of extra goodness between the request body and your API.

You can find the documentation here.

Joi allows you to validate any object, although it doesn’t have to be your request body it seems as though this is what most people use it for. I personally am using it with Node.JS and Express to validate my request body before it gets hashed and saved to my database.

const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required()
})

This is part of the example that the documentation gives on how to setup validation. As you can see there are methods that exist off of the Joi object. These functions are the layers of validation that the value passes through in order to make sure that the value is accepted.

I’ve seen many people use Regex for validation, and although this works its a little more complex then having something handy like Joi.

After you have declared your Schema you can access a method off of it called .validate() that you can pass the object you want to evaluate. The response returned from the method will be an object that either matches the object you passed in, or an object that includes an error with what was not correctly validated.

This blog post was just to share what I have learned about Joi so far, it looks like there are tons of other things you can do with the library, but the use case described in this blog post was what intrigued me most about the library.

Let me know what you think? And if you’ve worked with other similar libraries that you enjoy.

 
Share this