joi

Object validation is a tricky thing. It sounds pretty simple when you first think about it, yet there are a ton of libraries that try to do it. Why is that? I feel like there are just alot of way to approach the subject. joi (GitHub: spumko/joi, License: BSD 4-Clause) is a schema validation library that came out of the Walmart Labs efforts and more specifically power validation in the hapi server framework.

Lets check it out!

 

1
npm install joi

Usage

joi works by defining a schema. You can validate a single string or number:

1
2
3
4
5
6
7
8
9
10
var Joi = require('joi');
// will fail
Joi.string().validate(10, console.log);
// also will fail
Joi.string().email().validate('hello+gmail.com', console.log);
// will pass
Joi.string().email().validate('hello+world@gmail.com', console.log);

You can validate a basic plain schema

1
2
3
4
5
6
7
var schema = {counter: Joi.number().min(1).max(10).required()};
// will fail
Joi.validate({counter: 0}, schema, console.log);
// will pass
Joi.validate({counter: 5}, schema, console.log);

Finally, you can do a some pretty complicated validation with fields depending on each other:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/),
    confirmation: Joi.ref('password')
  })
  .with('password', 'confirmation');
// will fail because `foo` isn't in the schema at all
Joi.validate({foo: 1}, schema, console.log);
// will fail because `confirmation` is missing
Joi.validate({username: 'alex', password: 'qwerty'}, schema, console.log);
// will pass
Joi.validate({
  username: 'alex', password: 'qwerty', confirmation: 'qwerty'
}, schema, console.log);

Closing thoughts

Here are some other modules you might want to evaluate:

Finally, check out source code for this article on GitHub and an interative example on Runnable.

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published.