| name | joi |
| description | Use when building joi schemas, validating input data, defining custom types, conditional validation with .when(), cross-field references, custom error messages, or writing joi extensions. Standalone package that integrates with the hapijs ecosystem. |
Joi
Quick Start
const Joi = require('joi');
const schema = Joi.object({
name: Joi.string().min(1).max(100).required(),
age: Joi.number().integer().min(0),
email: Joi.string().email()
});
const { error, value } = schema.validate(input);
Critical Rules
- Schemas are immutable - Every method returns a new schema instance; never mutate
- Validate at boundaries - Use
validate() or attempt() at input boundaries; see validation
- Types extend base - All types inherit from
any(); see types overview
- Refs for cross-field - Use
Joi.ref() for dynamic values across fields; see references
- Extend for custom types - Use
Joi.extend() to create custom types; see extensions
Workflow
- Choose a type - types overview for all built-in types
- Add constraints - Chain rules like
.min(), .max(), .pattern(), .valid()
- Compose schemas - Nest
Joi.object(), Joi.array(), Joi.alternatives()
- Add conditionals - Use
.when() for dynamic schemas; see conditionals
- Customize errors - Override messages via
.messages() or .error(); see errors
Common Patterns
Conditional validation with .when()
const schema = Joi.object({
type: Joi.string().valid('email', 'sms').required(),
address: Joi.when('type', {
is: 'email',
then: Joi.string().email().required(),
otherwise: Joi.string().pattern(/^\+?[1-9]\d{1,14}$/).required()
})
});
Cross-field references with Joi.ref()
const schema = Joi.object({
password: Joi.string().min(8).required(),
confirmPassword: Joi.string().valid(Joi.ref('password')).required()
.messages({ 'any.only': 'passwords must match' }),
startDate: Joi.date().required(),
endDate: Joi.date().greater(Joi.ref('startDate')).required()
});
Key Patterns