CtrlK
BlogDocsLog inGet started
Tessl Logo

alonso-skills/joi

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 @hapi ecosystem.

100

Quality

100%

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Passed

No known issues

Overview
Quality
Evals
Security
Files

errors.mdreference/

Error Handling

ValidationError structure

const { error } = schema.validate(value);

error.message;    // Human-readable summary
error.details;    // Array of error detail objects
error.annotate(); // Annotated version of the input

Each detail object:

{
    message: '"name" is required',
    path: ['user', 'name'],          // Key path to the error
    type: 'any.required',            // Error code
    context: {
        label: 'user.name',          // Auto-generated label
        key: 'name',                 // Immediate key
        value: undefined             // The failing value
    }
}

Joi.isError(err)

Returns true if the error is a joi ValidationError.

Joi.ValidationError

The ValidationError constructor. Useful for instanceof checks.

Customizing error messages

.messages(messages) - Override specific error codes

Joi.string().min(3).max(30).messages({
    'string.base': '{{#label}} must be text',
    'string.min': '{{#label}} must be at least {{#limit}} characters',
    'string.max': '{{#label}} cannot exceed {{#limit}} characters',
    'any.required': '{{#label}} is required'
});

.message(message) - Override for last rule only

Joi.string().min(3).message('Too short').max(30).message('Too long');

.label(name) - Set the field label

Joi.string().label('Username').required();
// Error: "Username" is required

.error(err) - Completely override the error

// Static error
Joi.string().error(new Error('Invalid input'));

// Dynamic error
Joi.string().error((errors) => {
    return new Error(`Got ${errors.length} validation errors`);
});

Error message template variables

Available in .messages() templates:

VariableDescription
#labelField label (auto or from .label())
#valueThe failing value
#keyThe immediate object key
#limitRule argument (min, max, length)
#typeExpected type
#nameRule name
#regexPattern source
#validsList of allowed values
#invalidsList of denied values
#encodingString encoding

Error codes by type

Common error codes:

CodeWhen
any.requiredRequired field missing
any.unknownUnknown key in object
any.invalidValue in .invalid() list
any.onlyValue not in .valid() list
string.baseNot a string
string.emptyEmpty string
string.minBelow minimum length
string.maxAbove maximum length
string.emailInvalid email
string.pattern.baseRegex mismatch
number.baseNot a number
number.minBelow minimum
number.maxAbove maximum
number.integerNot an integer
date.baseNot a valid date
object.baseNot an object
object.unknownUnknown key
array.baseNot an array
array.minBelow minimum items
array.includesRequiredUnknownsMissing required item type

.warning(code, [context])

Emit a warning instead of an error. Warnings are collected but don't fail validation:

const schema = Joi.string().warning('custom.deprecation', { alt: 'newField' });

const { value, warning } = schema.validate('test', { warnings: true });
// warning.details[0].type === 'custom.deprecation'

error.annotate([stripColors])

Returns a string with the input annotated with error markers. Useful for debugging:

const { error } = Joi.object({
    a: Joi.number()
}).validate({ a: 'not a number' });

console.log(error.annotate());
// {
//   "a" [1]: "not a number"
// }
//
// [1] "a" must be a number

reference

any.md

conditionals.md

errors.md

extensions.md

metadata.md

references.md

testing.md

types.md

validation.md

SKILL.md

tile.json