Object schema validation library for JavaScript with comprehensive validation capabilities
npx @tessl/cli install tessl/npm-joi@18.0.0Joi is a powerful schema description language and data validator for JavaScript that provides comprehensive object schema validation capabilities. It offers an expressive API for defining validation rules, data transformation, and error handling for JavaScript objects and values with built-in support for common data types, format validation, and the ability to create reusable schema patterns.
npm install joiconst Joi = require('joi');For ES modules:
import Joi from 'joi';TypeScript:
import * as Joi from 'joi';const Joi = require('joi');
// Define a schema
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
});
// Validate data
const { error, value } = schema.validate({
username: 'abc',
email: 'test@example.com'
});
if (error) {
console.log(error.details[0].message);
} else {
console.log('Valid data:', value);
}
// Async validation
try {
const value = await schema.validateAsync({
username: 'abc',
email: 'test@example.com'
});
console.log('Valid data:', value);
} catch (error) {
console.log('Validation error:', error.message);
}Joi is built around several key components:
Core schema types for validating different data types with extensive configuration options and validation rules.
function any(): AnySchema;
function string(): StringSchema;
function number(): NumberSchema;
function boolean(): BooleanSchema;
function array(): ArraySchema;
function object(schema?: SchemaMap): ObjectSchema;
function date(): DateSchema;
function function(): FunctionSchema;
function binary(): BinarySchema;
function symbol(): SymbolSchema;
function alternatives(...types: SchemaLike[]): AlternativesSchema;
function link(ref?: string): LinkSchema;
// Type aliases
const bool: typeof boolean;
const func: typeof function;
const alt: typeof alternatives;Core validation functions for executing validation with comprehensive error handling and configuration options.
function assert(value: any, schema: Schema, message?: string | Error, options?: ValidationOptions): any;
function attempt(value: any, schema: Schema, message?: string | Error, options?: ValidationOptions): any;
function compile(schema: SchemaLike, options?: CompileOptions): Schema;
function checkPreferences(prefs: ValidationOptions): void;Dynamic validation system supporting field references, context access, and template expressions for advanced validation scenarios.
function ref(key: string, options?: ReferenceOptions): Reference;
function in(ref: string, options?: ReferenceOptions): Reference;
function expression(template: string, options?: any): Template;
const x: typeof expression;
interface Reference {
readonly isContext: boolean;
readonly isGlobal: boolean;
readonly key: string;
readonly path: string[];
readonly ancestor: number;
}
interface Template {
readonly isTemplate: boolean;
render(context: any, prefs?: any, local?: any, options?: any): string;
}Extension system for creating custom schema types, validation rules, and modifying default behavior.
function extend(...extensions: Extension[]): Root;
function defaults(modifier: (schema: AnySchema) => AnySchema): Root;
interface Extension {
type: string | RegExp;
base?: Schema;
messages?: Record<string, string>;
coerce?: (value: any, helpers: CustomHelpers) => CoerceResult;
pre?: (value: any, helpers: CustomHelpers) => any;
language?: Record<string, string>;
describe?: (description: SchemaDescription) => SchemaDescription;
rules?: Record<string, RuleOptions>;
overrides?: Record<string, any>;
rebuild?: (schema: Schema) => Schema;
manifest?: ManifestOptions;
args?: (schema: Schema, ...args: any[]) => Schema;
}Helper functions for type checking, introspection, and working with joi objects and errors.
function isSchema(schema: any, options?: any): boolean;
function isRef(ref: any): boolean;
function isExpression(expression: any): boolean;
function isError(error: any): boolean;
function types(): Record<string, Schema>;
const version: string;
const cache: CacheProvider;
const override: symbol;interface ValidationOptions {
abortEarly?: boolean;
allowUnknown?: boolean;
cache?: boolean;
context?: any;
convert?: boolean;
dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc';
debug?: boolean;
errors?: ErrorFormattingOptions;
externals?: boolean;
messages?: LanguageMessages;
nonEnumerables?: boolean;
noDefaults?: boolean;
presence?: PresenceMode;
skipFunctions?: boolean;
stripUnknown?: boolean | { arrays?: boolean; objects?: boolean };
warnings?: boolean;
}
interface ErrorFormattingOptions {
escapeHtml?: boolean;
label?: 'path' | 'key' | false;
language?: string;
render?: boolean;
stack?: boolean;
wrap?: {
label?: string | false;
array?: string | false;
string?: string | false;
};
}
interface ValidationError extends Error {
name: 'ValidationError';
isJoi: true;
details: ValidationErrorItem[];
_original: any;
annotate(): string;
}
interface ValidationErrorItem {
message: string;
path: (string | number)[];
type: string;
context?: any;
}
interface ValidationResult<T = any> {
error?: ValidationError;
value: T;
warning?: ValidationError;
}
type PresenceMode = 'optional' | 'required' | 'forbidden';
type LanguageMessages = Record<string, string | Record<string, string>>;