This post was written for Nodejitsu blog and is crossposted here. Nodejitsu loved what I was doing at npmawesome.com and is now supporting the project.


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!

npm install joi

Usage

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

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

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:

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.