or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

extensions-customization.mdindex.mdreferences-expressions.mdschema-types.mdutility-functions.mdvalidation-methods.md
tile.json

tessl/npm-joi

Object schema validation library for JavaScript with comprehensive validation capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/joi@18.0.x

To install, run

npx @tessl/cli install tessl/npm-joi@18.0.0

index.mddocs/

Joi

Joi 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.

Package Information

  • Package Name: joi
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install joi
  • Node.js Requirements: >= 20

Core Imports

const Joi = require('joi');

For ES modules:

import Joi from 'joi';

TypeScript:

import * as Joi from 'joi';

Basic Usage

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);
}

Architecture

Joi is built around several key components:

  • Schema Types: Core validation types (string, number, object, array, etc.) providing type-specific validation rules
  • Validation Engine: Synchronous and asynchronous validation with detailed error reporting
  • Reference System: Dynamic validation using references to other fields or context values
  • Extension System: Plugin architecture for custom validation types and rules
  • Template System: Dynamic message generation and value interpolation

Capabilities

Schema Types

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;

Schema Types

Validation Methods

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;

Validation Methods

References and Expressions

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;
}

References and Expressions

Extensions and Customization

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;
}

Extensions and Customization

Utility Functions

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;

Utility Functions

Global Configuration Types

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>>;