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 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!
1
|
npm install joi |
Usage
joi works by defining a schema. You can validate a single string or number:
1
2
3
4
5
6
7
8
9
10
|
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
1
2
3
4
5
6
7
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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:
- validator is a string validation and sanitization module by Chris O’Hara.
- finito is a language for capturing information structure by Louis Lambeau.
- schema-inspector is a module to sanitize and validate objects by Sébastien Chopin (previously featured on npmawesome.com).
Finally, check out source code for this article on GitHub and an interative example on Runnable.