Save time managing and deploying your node.js app

Nodejitsu has joined GoDaddy

We are excited to join GoDaddy to help spearhead their largest Node.js product: Website Builder. Please read our blog post to learn more about customer transition plans and our continued support for Open Source within the node community.

Want to know all the details?
Read the full blog post or read the GoDaddy Announcement.

npmawesome: Object schema validation with Joi

About the author

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

This is a guest post from Alex Gorbatchev and Nodejitsu loved what Alex was doing at 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  


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('', console.log);

// will pass
Joi.string().email().validate('', 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
  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.