Nodejitsu

Save time managing and deploying your node.js app

npmawesome: Object schema validation with Joi

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

Other popular posts

- Scaling Isomorphic Javascript Code - Keep a node.js server up with Forever - Package.json dependencies done right
- npm cheat sheet - 6 Must Have Node.js Modules
Sign up to our platform for free - get $20 usage

This is a guest post from Alex Gorbatchev and npmawesome.com. Nodejitsu loved what Alex was doing at npmawesome.com and is now supporting the project. Like what you see here? Why don't you contribute on Github?


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.