Joi
Want to read about the joi JavaScript library. It seems like it would be a great library to use to simplify data validation.
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 address
- Validate email address and domain
- joi formula
- Math and string formula parser
- joi-date
- Extensions for advance date rules
- joi pinpoint
- Return the filename and line number of the calling function
- joi tlds
- TLDS list for domain validation
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:
- 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
- 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.
Comments
You can read more about how comments are sorted in this blog post.
User Comments
There are currently no comments for this article.