Joi

Want to read about the joi JavaScript library. It seems like it would be a great library to use to simplify data validation.

Date Created:
1 45

References



Notes


I want to look into Joi because it was recommended by Socket.IO for validating WebSocket messages sent as JSON and because I think it could help simplify code and make it more readable.

The most powerful schema description language and data validator for JavaScript.

joi lets you describe your data using a simple, intuitive, and readable language.

const Joi = require('joi');

const schema = Joi.object({
username: Joi.string() // Username: must be string,
.alphanum() // only contain alphanumeric characters,
.min(3) // at least 3 characters long,
.max(30) // at most 30 characters long,
.required(), // required

password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')), //optional string that must match pattern

repeat_password: Joi.ref('password'),

access_token: [
Joi.string(),
Joi.number()
],

birth_year: Joi.number() // number between 1900 and 2013
.integer()
.min(1900)
.max(2013),

email: Joi.string() // valud email address string, TLD must be .com or .net
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
.with('username', 'birth_year')
.xor('password', 'access_token') // only password or access_token can be included in submission
.with('password', 'repeat_password');


schema.validate({ username: 'abc', birth_year: 1994 });
// -> { value: { username: 'abc', birth_year: 1994 } }

schema.validate({});
// -> { value: {}, error: '"username" is required' }

// Also -

try {
const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });
}
catch (err) { }

General Usage

Usage is a two steps process:

  1. A schema is constructed using the provisioned types and constraints:
const schema = Joi.object({
a: Joi.string()
});
  • joi schema objects are immutable - every additional rule added will return a new schema object
  1. The value is validated against the defined schema:
const { error, value } = schema.validate({ a: 'a string' });

If the input is valid, then the error will be undefined. If the input is invalid, error is assigned a ValidationError object providing more information.

When validating a schema:

  • Values (or keys in the case of objects) are optional by default
  • Strings are utf-8 encoded by default.
  • Rules are defined in additive fashion and evaluated in order, first the inclusive rules, then the exclusive rules.

You can read more about how comments are sorted in this blog post.

User Comments

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Files

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Upload Previous Version of Editor State

ESC