CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-joi

Object schema validation library for JavaScript with comprehensive validation capabilities

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

schema-types.mddocs/

Schema Types

Joi provides comprehensive schema types for validating different data types with extensive configuration options and validation rules.

Capabilities

Any Schema

Base schema type that matches any data type and provides fundamental validation methods.

/**
 * Creates a schema that matches any data type
 * @returns AnySchema instance with base validation methods
 */
function any(): AnySchema;

interface AnySchema<T = any> {
  // Value constraints
  allow(...values: any[]): this;
  disallow(...values: any[]): this;
  valid(...values: any[]): this;
  invalid(...values: any[]): this;
  equal(...values: any[]): this;
  only(...values: any[]): this;
  
  // Presence modifiers
  required(): this;
  optional(): this;
  forbidden(): this;
  exist(): this;
  
  // Default and failover values
  default(value?: any | Reference | ((parent: any, helpers: CustomHelpers) => any), description?: string): this;
  failover(value?: any | Reference | ((parent: any, helpers: CustomHelpers) => any), description?: string): this;
  empty(schema?: SchemaLike): this;
  
  // Conditional validation
  when(condition: string | Reference | Schema, options: WhenOptions): this;
  when(condition: Schema, options: WhenSchemaOptions): this;
  
  // Custom validation
  custom(method: CustomValidator, description?: string): this;
  external(method: ExternalValidator, description?: string): this;
  
  // Metadata and documentation
  description(desc: string): this;
  example(value: any, options?: ExampleOptions): this;
  meta(meta: any): this;
  note(note: string): this;
  tag(...tags: string[]): this;
  label(name: string): this;
  id(id?: string): this;
  
  // Schema manipulation
  concat(schema: this): this;
  fork(paths: string | string[], adjuster: (schema: Schema) => Schema): this;
  extract(paths: string | string[]): Schema;
  unknown(allow?: boolean): this;
  
  // Validation execution
  validate(value: any, options?: ValidationOptions): ValidationResult<T>;
  validateAsync(value: any, options?: ValidationOptions): Promise<T>;
  attempt(value: any, options?: ValidationOptions): T;
  assert(value: any, options?: ValidationOptions): T;
  
  // Introspection
  describe(): SchemaDescription;
  type: string;
  $: this;
  
  // Configuration
  prefs(preferences: ValidationOptions): this;
  preferences(preferences: ValidationOptions): this;
  options(options: ValidationOptions): this;
  strict(isStrict?: boolean): this;
  
  // Rules and messages
  rule(options: RuleOptions): this;
  message(message: string | LanguageMessages): this;
  error(err: Error | string | ((errors: ErrorReport[]) => Error | string)): this;
  warn(): this;
  
  // Caching and performance
  cache(cache?: boolean): this;
  
  // Schema chaining
  keep(): this;
  strip(): this;
}

String Schema

Schema for validating string values with format validation, length constraints, and pattern matching.

/**
 * Creates a string validation schema
 * @returns StringSchema with string-specific validation methods
 */
function string(): StringSchema;

interface StringSchema extends AnySchema<string> {
  // Length validation
  length(limit: number | Reference): this;
  min(limit: number | Reference): this;
  max(limit: number | Reference): this;
  
  // Pattern matching
  pattern(regex: RegExp, options?: PatternOptions): this;
  regex(regex: RegExp, options?: PatternOptions): this;
  replace(pattern: RegExp | string, replacement: string): this;
  
  // Character set validation
  alphanum(): this;
  token(): this;
  hex(options?: HexOptions): this;
  base64(options?: Base64Options): this;
  
  // Format validation
  creditCard(): this;
  dataUri(options?: DataUriOptions): this;
  domain(options?: DomainOptions): this;
  email(options?: EmailOptions): this;
  guid(options?: GuidOptions): this;
  uuid(options?: UuidOptions): this;
  hostname(): this;
  ip(options?: IpOptions): this;
  uri(options?: UriOptions): this;
  isoDate(): this;
  isoDuration(): this;
  
  // Case operations
  lowercase(): this;
  uppercase(): this;
  case(direction: 'upper' | 'lower'): this;
  
  // String manipulation
  trim(enabled?: boolean): this;
  truncate(enabled?: boolean): this;
  normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this;
}

interface EmailOptions {
  allowUnicode?: boolean;
  ignoreLength?: boolean;
  minDomainSegments?: number;
  multiple?: boolean;
  separator?: string | string[];
  tlds?: boolean | { allow?: Set<string> | string[] | boolean; deny?: Set<string> | string[] };
}

interface UriOptions {
  allowRelative?: boolean;
  allowQuerySquareBrackets?: boolean;
  domain?: DomainOptions;
  relativeOnly?: boolean;
  scheme?: string | RegExp | Array<string | RegExp>;
}

Number Schema

Schema for validating numeric values with range constraints and precision control.

/**
 * Creates a number validation schema
 * @returns NumberSchema with number-specific validation methods
 */
function number(): NumberSchema;

interface NumberSchema extends AnySchema<number> {
  // Range validation
  min(limit: number | Reference): this;
  max(limit: number | Reference): this;
  greater(limit: number | Reference): this;
  less(limit: number | Reference): this;
  
  // Sign validation
  positive(): this;
  negative(): this;
  sign(sign: 'positive' | 'negative'): this;
  
  // Type constraints
  integer(): this;
  precision(limit: number): this;
  multiple(base: number | Reference): this;
  port(): this;
  unsafe(enabled?: boolean): this;
}

Boolean Schema

Schema for validating boolean values with truthy/falsy value conversion.

/**
 * Creates a boolean validation schema
 * @returns BooleanSchema with boolean-specific validation methods
 */
function boolean(): BooleanSchema;

interface BooleanSchema extends AnySchema<boolean> {
  // Conversion options
  truthy(...values: any[]): this;
  falsy(...values: any[]): this;
  sensitive(enabled?: boolean): this;
}

Array Schema

Schema for validating arrays with element validation and length constraints.

/**
 * Creates an array validation schema
 * @returns ArraySchema with array-specific validation methods
 */
function array(): ArraySchema;

interface ArraySchema<T = any> extends AnySchema<T[]> {
  // Element validation
  items(...schemas: SchemaLike[]): this;
  ordered(...schemas: SchemaLike[]): this;
  has(schema: SchemaLike): this;
  
  // Length constraints
  length(limit: number | Reference): this;
  min(limit: number | Reference): this;
  max(limit: number | Reference): this;
  
  // Array properties
  sparse(enabled?: boolean): this;
  single(enabled?: boolean): this;
  unique(comparator?: string | ((a: any, b: any) => boolean), options?: UniqueOptions): this;
  sort(options?: SortOptions): this;
}

interface UniqueOptions {
  ignoreUndefined?: boolean;
}

interface SortOptions {
  order?: 'ascending' | 'descending';
  by?: string | Reference;
}

Object Schema

Schema for validating objects with key validation and relationship constraints.

/**
 * Creates an object validation schema
 * @param schema Optional object schema mapping
 * @returns ObjectSchema with object-specific validation methods
 */
function object(schema?: SchemaMap): ObjectSchema;

interface ObjectSchema<T = any> extends AnySchema<T> {
  // Key management
  keys(schema?: SchemaMap): this;
  append(schema: SchemaMap): this;
  unknown(allow?: boolean): this;
  
  // Key relationships
  and(...peers: string[]): this;
  nand(...peers: string[]): this;
  or(...peers: string[]): this;
  xor(...peers: string[]): this;
  oxor(...peers: string[]): this;
  with(key: string, peers: string | string[]): this;
  without(key: string, peers: string | string[]): this;
  
  // Key requirements
  requiredKeys(...keys: string[]): this;
  optionalKeys(...keys: string[]): this;
  forbiddenKeys(...keys: string[]): this;
  
  // Pattern matching
  pattern(pattern: RegExp | Schema, schema: SchemaLike, options?: PatternOptions): this;
  
  // Object validation
  length(limit: number): this;
  min(limit: number): this;
  max(limit: number): this;
  
  // Type constraints
  instance(constructor: Function, name?: string): this;
  schema(type?: SchemaLike): this;
  
  // Assertions
  assert(ref: string | Reference, schema: SchemaLike, message?: string): this;
}

type SchemaMap<T = any> = {
  [K in keyof T]?: SchemaLike<T[K]>;
};

Date Schema

Schema for validating Date objects with timestamp and range validation.

/**
 * Creates a date validation schema
 * @returns DateSchema with date-specific validation methods
 */
function date(): DateSchema;

interface DateSchema extends AnySchema<Date> {
  // Range validation
  greater(date: 'now' | Date | number | string | Reference): this;
  less(date: 'now' | Date | number | string | Reference): this;
  min(date: 'now' | Date | number | string | Reference): this;
  max(date: 'now' | Date | number | string | Reference): this;
  
  // Format validation
  iso(): this;
  timestamp(type?: 'javascript' | 'unix'): this;
}

Function Schema

Schema for validating function objects with arity and class constraints.

/**
 * Creates a function validation schema
 * @returns FunctionSchema with function-specific validation methods
 */
function function(): FunctionSchema;

interface FunctionSchema extends AnySchema<Function> {
  // Function properties
  arity(n: number): this;
  minArity(n: number): this;
  maxArity(n: number): this;
  class(): this;
}

Binary Schema

Schema for validating Buffer objects with encoding and length constraints.

/**
 * Creates a binary validation schema (conditionally available)
 * @returns BinarySchema with binary-specific validation methods
 */
function binary(): BinarySchema;

interface BinarySchema extends AnySchema<Buffer> {
  // Length constraints
  length(limit: number | Reference): this;
  min(limit: number | Reference): this;
  max(limit: number | Reference): this;
  
  // Encoding
  encoding(encoding: string): this;
}

Symbol Schema

Schema for validating Symbol values with mapping support.

/**
 * Creates a symbol validation schema
 * @returns SymbolSchema with symbol-specific validation methods
 */
function symbol(): SymbolSchema;

interface SymbolSchema extends AnySchema<symbol> {
  // Value mapping
  map(iterable: Iterable<[any, symbol]> | { [key: string]: symbol }): this;
}

Alternatives Schema

Schema for validating against multiple possible schema types.

/**
 * Creates an alternatives validation schema
 * @param types Optional alternative schema types
 * @returns AlternativesSchema with alternatives-specific validation methods
 */
function alternatives(...types: SchemaLike[]): AlternativesSchema;

interface AlternativesSchema<T = any> extends AnySchema<T> {
  // Alternative matching
  try<A>(a: SchemaLike<A>): AlternativesSchema<A>;
  try<A, B>(a: SchemaLike<A>, b: SchemaLike<B>): AlternativesSchema<A | B>;
  try<A, B, C>(a: SchemaLike<A>, b: SchemaLike<B>, c: SchemaLike<C>): AlternativesSchema<A | B | C>;
  
  // Conditional logic
  conditional(ref: string | Reference, options: WhenOptions): this;
  conditional(ref: Schema, options: WhenSchemaOptions): this;
  
  // Matching mode
  match(mode: 'any' | 'all' | 'one'): this;
}

Link Schema

Schema for creating references to other schemas, enabling recursive validation.

/**
 * Creates a link validation schema for recursive structures
 * @param ref Optional reference to link to
 * @returns LinkSchema with link-specific validation methods
 */
function link(ref?: string): LinkSchema;

interface LinkSchema<T = any> extends AnySchema<T> {
  // Schema linking
  concat(schema: SchemaLike): this;
  link(ref?: string): this;
}

Type Aliases

// Convenience aliases for common schema types
const bool: typeof boolean;
const func: typeof function;
const alt: typeof alternatives;

Usage Examples

Basic String Validation:

const schema = Joi.string().min(3).max(50).required();
const { error, value } = schema.validate('hello');

Object Validation with Nested Schemas:

const userSchema = Joi.object({
    name: Joi.string().required(),
    email: Joi.string().email().required(),
    age: Joi.number().integer().min(18),
    preferences: Joi.object({
        theme: Joi.string().valid('light', 'dark'),
        notifications: Joi.boolean()
    })
});

Array Validation:

const listSchema = Joi.array()
    .items(Joi.string().min(1))
    .min(1)
    .max(10)
    .unique();

Alternatives Schema:

const mixedSchema = Joi.alternatives().try(
    Joi.string(),
    Joi.number(),
    Joi.boolean()
);

docs

extensions-customization.md

index.md

references-expressions.md

schema-types.md

utility-functions.md

validation-methods.md

tile.json