Joi for Node: Exploring Javascript Object Schema Validation

Adopt Object Schema Validation for your NodeJS Projects

Joi for the browser? No — use Yup Instead

A Simple Example of Joi Schema

const schema = Joi.object().keys({
username: Joi.string().alphanum().min(6).max(16).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{6,16}$/).min(6).required()
}).with('username', 'password');

Joi .object()

keys()

We can also define schema without using keys(), when there is only one set of keys

const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(16).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).min(6).required()
}).with('username', 'password');

username and password schema

username: Joi.string().alphanum().min(6).max(16).required(),
password: Joi.string().regex(/^[a-zA-Z0-9{6,16}$/)

with(key, peers)

Using keys()

//define base object
const base = Joi.object().keys({
a: Joi.number(),
b: Joi.string()
});
// add a c key onto base schema
const extended = base.keys({
c: Joi.boolean()
});

Some Useful Joi Schema Methods (Constraints)

const schema = Joi.string().email();

Numbers

Strings

Dates

Arrays

const schema = Joi.array().items(Joi.string(), Joi.number()); 
// array may contain strings and numbers

Objects

Miscellaneous Constraints of Interest

Validation

let myObj = {
username: req.body.username,
password: req.body.password
};
const result = await Joi.validate(myObj, schema);
//async / await
myAsyncFunction = async (value, schema) => {
const promise = await Joi.validate(value, schema);

//handle result
}
//or then()
const promise = await Joi.validate(value, schema).then(value => {
// value -> { "a" : 123 }
});

attempt() and assert()

assert(value, schema, [message])
attempt(value, schema, [message])

describe() and compile()

Using defaults()

defaults() — supply default schema to new schemas

const defaultJoi = Joi.defaults(schema => (
schema.min(1).max(20).required().integer()
));
const schema = defaultJoi.object();
//Joi.object().min(1).max(20).required().integer()

Where to go From Here

yarn add joi

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store