CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yup

Dead simple Object schema validation

Overview
Eval results
Files

schema-types.mddocs/

Schema Types

Schema types are the core building blocks of yup validation. Each schema type provides specific validation methods tailored to its data type, while inheriting common functionality from the base Schema class.

Capabilities

Schema Factory Functions

Functions that create new schema instances for different data types.

/**
 * Creates a schema for validating any type of value
 * @param spec - Optional mixed schema configuration
 * @returns MixedSchema instance
 */
function mixed<T = any>(spec?: MixedOptions): MixedSchema<T>;

/**
 * Creates a schema for validating string values
 * @returns StringSchema instance
 */
function string(): StringSchema;

/**
 * Creates a schema for validating number values  
 * @returns NumberSchema instance
 */
function number(): NumberSchema;

/**
 * Creates a schema for validating boolean values
 * @returns BooleanSchema instance
 */
function boolean(): BooleanSchema;

/**
 * Alias for boolean() function
 * @returns BooleanSchema instance
 */
function bool(): BooleanSchema;

/**
 * Creates a schema for validating Date objects
 * @returns DateSchema instance
 */
function date(): DateSchema;

/**
 * Creates a schema for validating object structures
 * @param shape - Object shape definition with field schemas
 * @returns ObjectSchema instance
 */
function object<T extends ObjectShape = {}>(shape?: T): ObjectSchema<T>;

/**
 * Creates a schema for validating arrays
 * @param innerType - Schema for validating array elements
 * @returns ArraySchema instance
 */
function array<T = any>(innerType?: Schema<T>): ArraySchema<T>;

/**
 * Creates a schema for validating tuples with fixed element types
 * @param types - Array of schemas for each tuple position
 * @returns TupleSchema instance
 */
function tuple<T extends readonly [...any[]]>(types: T): TupleSchema<T>;

interface MixedOptions {
  type?: string;
  check?: (value: any) => boolean;
}

type ObjectShape = Record<string, Schema>;

Base Schema Methods

All schema types inherit these core methods from the base Schema class.

/**
 * Create a copy of the schema with optional modifications
 * @param spec - Modifications to apply to the cloned schema
 * @returns New schema instance
 */
clone(spec?: Partial<SchemaSpec>): this;

/**
 * Merge this schema with another schema
 * @param schema - Schema to merge with
 * @returns New merged schema
 */
concat(schema: Schema): Schema;

/**
 * Set a default value for the schema
 * @param value - Default value or factory function
 * @returns New schema with default value
 */
default<D>(value: D | (() => D)): Schema;

/**
 * Enable or disable strict validation mode
 * @param isStrict - Whether to enable strict mode
 * @returns New schema with strict mode setting
 */
strict(isStrict?: boolean): this;

/**
 * Enable or disable field stripping in parent objects
 * @param enabled - Whether to strip this field
 * @returns New schema with strip setting
 */
strip(enabled?: boolean): this;

Optionality & Nullability

Methods for controlling whether values are required and handling null/undefined values.

/**
 * Mark the schema as required (no undefined values allowed)
 * @param message - Custom error message
 * @returns New required schema
 */
required(message?: string): Schema;

/**
 * Mark the schema as optional (undefined values allowed)
 * @returns New optional schema
 */
notRequired(): Schema;

/**
 * Mark the schema as optional (alias for notRequired)
 * @returns New optional schema
 */
optional(): Schema;

/**
 * Require the value to be defined (no undefined values)
 * @param message - Custom error message
 * @returns New schema that rejects undefined
 */
defined(message?: string): Schema;

/**
 * Allow null values
 * @param message - Custom error message for type conversion
 * @returns New schema that accepts null
 */
nullable(message?: string): Schema;

/**
 * Disallow null values
 * @param message - Custom error message
 * @returns New schema that rejects null
 */
nonNullable(message?: string): Schema;

Value Constraints

Methods for constraining valid values using whitelists and blacklists.

/**
 * Allow only specific values (whitelist)
 * @param arrayOfValues - Array of allowed values
 * @param message - Custom error message
 * @returns New schema with value constraint
 */
oneOf<U extends T>(arrayOfValues: ReadonlyArray<U>, message?: string): Schema<U>;

/**
 * Disallow specific values (blacklist)
 * @param arrayOfValues - Array of disallowed values
 * @param message - Custom error message
 * @returns New schema with value constraint
 */
notOneOf(arrayOfValues: ReadonlyArray<T>, message?: string): Schema;

// Aliases for oneOf
equals<U extends T>(arrayOfValues: ReadonlyArray<U>, message?: string): Schema<U>;
is<U extends T>(arrayOfValues: ReadonlyArray<U>, message?: string): Schema<U>;

// Aliases for notOneOf
not(arrayOfValues: ReadonlyArray<T>, message?: string): Schema;
nope(arrayOfValues: ReadonlyArray<T>, message?: string): Schema;

String Schema

Specialized schema for string validation with string-specific methods.

/**
 * Validate exact string length
 * @param length - Required string length
 * @param message - Custom error message
 * @returns New schema with length constraint
 */
length(length: number, message?: string): StringSchema;

/**
 * Validate minimum string length
 * @param min - Minimum allowed length
 * @param message - Custom error message
 * @returns New schema with minimum length constraint
 */
min(min: number, message?: string): StringSchema;

/**
 * Validate maximum string length
 * @param max - Maximum allowed length
 * @param message - Custom error message
 * @returns New schema with maximum length constraint
 */
max(max: number, message?: string): StringSchema;

/**
 * Validate string against regular expression pattern
 * @param regex - Regular expression to match
 * @param options - Match options or custom error message
 * @returns New schema with regex constraint
 */
matches(regex: RegExp, options?: string | MatchOptions): StringSchema;

/**
 * Validate email format
 * @param message - Custom error message
 * @returns New schema with email validation
 */
email(message?: string): StringSchema;

/**
 * Validate URL format
 * @param message - Custom error message
 * @returns New schema with URL validation
 */
url(message?: string): StringSchema;

/**
 * Validate UUID format
 * @param message - Custom error message
 * @returns New schema with UUID validation
 */
uuid(message?: string): StringSchema;

/**
 * Validate ISO datetime format
 * @param options - Datetime validation options
 * @returns New schema with datetime validation
 */
datetime(options?: DateTimeOptions): StringSchema;

/**
 * Trim whitespace and validate the result
 * @param message - Custom error message for transformation
 * @returns New schema with trim transformation
 */
trim(message?: string): StringSchema;

/**
 * Convert to lowercase and validate the result
 * @param message - Custom error message for transformation
 * @returns New schema with lowercase transformation
 */
lowercase(message?: string): StringSchema;

/**
 * Convert to uppercase and validate the result
 * @param message - Custom error message for transformation
 * @returns New schema with uppercase transformation
 */
uppercase(message?: string): StringSchema;

/**
 * Override for string schemas: require non-empty strings
 * For strings, required() validates that the string has a length > 0
 * @param message - Custom error message
 * @returns New required schema that rejects empty strings
 */
required(message?: string): StringSchema;

/**
 * Override for string schemas: remove the non-empty string requirement
 * @returns New optional schema that allows empty strings
 */
notRequired(): StringSchema;

/**
 * Ensure string is not null (converts null to empty string)
 * @returns New schema with null handling
 */
ensure(): StringSchema;

interface MatchOptions {
  message?: string;
  excludeEmptyString?: boolean;
}

interface DateTimeOptions {
  precision?: number;
  offset?: boolean;
  message?: string;
}

Number Schema

Specialized schema for number validation with numeric constraints.

/**
 * Validate minimum numeric value
 * @param min - Minimum allowed value
 * @param message - Custom error message
 * @returns New schema with minimum constraint
 */
min(min: number, message?: string): NumberSchema;

/**
 * Validate maximum numeric value
 * @param max - Maximum allowed value
 * @param message - Custom error message
 * @returns New schema with maximum constraint
 */
max(max: number, message?: string): NumberSchema;

/**
 * Validate value is strictly less than specified number
 * @param less - Upper bound (exclusive)
 * @param message - Custom error message
 * @returns New schema with less-than constraint
 */
lessThan(less: number, message?: string): NumberSchema;

/**
 * Validate value is strictly greater than specified number
 * @param more - Lower bound (exclusive)
 * @param message - Custom error message
 * @returns New schema with greater-than constraint
 */
moreThan(more: number, message?: string): NumberSchema;

/**
 * Validate value is positive (> 0)
 * @param message - Custom error message
 * @returns New schema with positive constraint
 */
positive(message?: string): NumberSchema;

/**
 * Validate value is negative (< 0)
 * @param message - Custom error message
 * @returns New schema with negative constraint
 */
negative(message?: string): NumberSchema;

/**
 * Validate value is an integer
 * @param message - Custom error message
 * @returns New schema with integer constraint
 */
integer(message?: string): NumberSchema;

/**
 * Truncate number to integer
 * @returns New schema with truncation transformation
 */
truncate(): NumberSchema;

/**
 * Round number using specified method
 * @param method - Rounding method ("ceil", "floor", "round", "trunc")
 * @returns New schema with rounding transformation
 */
round(method?: "ceil" | "floor" | "round" | "trunc"): NumberSchema;

Boolean Schema

Specialized schema for boolean validation.

/**
 * Validate value must be true
 * @param message - Custom error message
 * @returns New schema requiring true value
 */
isTrue(message?: string): BooleanSchema;

/**
 * Validate value must be false
 * @param message - Custom error message
 * @returns New schema requiring false value
 */
isFalse(message?: string): BooleanSchema;

Date Schema

Specialized schema for Date validation with date-specific constraints.

/**
 * Validate minimum date value
 * @param min - Minimum allowed date
 * @param message - Custom error message
 * @returns New schema with minimum date constraint
 */
min(min: Date | string | Reference, message?: string): DateSchema;

/**
 * Validate maximum date value
 * @param max - Maximum allowed date
 * @param message - Custom error message
 * @returns New schema with maximum date constraint
 */
max(max: Date | string | Reference, message?: string): DateSchema;

/**
 * Static property representing an invalid Date
 */
static INVALID_DATE: Date;

Object Schema

Specialized schema for object validation with structure definition and manipulation.

/**
 * Define or modify object shape
 * @param additions - Field schemas to add
 * @param excludes - Field names to exclude
 * @returns New schema with updated shape
 */
shape<U extends ObjectShape>(
  additions: U,
  excludes?: [string, string][]
): ObjectSchema<U>;

/**
 * Object containing field definitions
 */
fields: ObjectShape;

/**
 * Select only specified fields from object
 * @param keys - Field names to include
 * @returns New schema with selected fields only
 */
pick<K extends keyof T>(keys: K[]): ObjectSchema<Pick<T, K>>;

/**
 * Exclude specified fields from object
 * @param keys - Field names to exclude
 * @returns New schema without excluded fields
 */
omit<K extends keyof T>(keys: K[]): ObjectSchema<Omit<T, K>>;

/**
 * Make all fields optional
 * @returns New schema with all optional fields
 */
partial(): ObjectSchema<Partial<T>>;

/**
 * Make all fields recursively optional
 * @returns New schema with deeply optional fields
 */
deepPartial(): ObjectSchema<DeepPartial<T>>;

/**
 * Disallow unknown keys in object
 * @param allow - Whether to allow unknown keys
 * @param message - Custom error message
 * @returns New schema with unknown key handling
 */
noUnknown(allow?: boolean, message?: string): ObjectSchema;

/**
 * Configure unknown key handling
 * @param allow - Whether to allow unknown keys
 * @param message - Custom error message
 * @returns New schema with unknown key handling
 */
unknown(allow?: boolean, message?: string): ObjectSchema;

/**
 * Strip unknown keys from validated objects
 * @returns New schema that strips unknown keys
 */
stripUnknown(): ObjectSchema;

/**
 * Validate exact object shape without stripping
 * @param message - Custom error message
 * @returns New schema requiring exact shape
 */
exact(message?: string): ObjectSchema;

/**
 * Move or copy field values during validation
 * @param from - Source field name
 * @param to - Target field name  
 * @param alias - Whether to copy (true) or move (false)
 * @returns New schema with field transformation
 */
from(from: string, to: string, alias?: boolean): ObjectSchema;

/**
 * Parse JSON string to object during validation
 * @returns New schema with JSON parsing
 */
json(): ObjectSchema;

/**
 * Transform all object keys using provided function
 * @param fn - Key transformation function
 * @returns New schema with key transformation
 */
transformKeys(fn: (key: string) => string): ObjectSchema;

/**
 * Convert all keys to camelCase
 * @returns New schema with camelCase key transformation
 */
camelCase(): ObjectSchema;

/**
 * Convert all keys to snake_case
 * @returns New schema with snake_case key transformation
 */
snakeCase(): ObjectSchema;

/**
 * Convert all keys to CONSTANT_CASE
 * @returns New schema with CONSTANT_CASE key transformation
 */
constantCase(): ObjectSchema;

type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

Array Schema

Specialized schema for array validation with element type definition and array-specific constraints.

/**
 * Define schema for array elements
 * @param schema - Schema to validate each array element
 * @returns New schema with element validation
 */
of<U>(schema: Schema<U>): ArraySchema<U>;

/**
 * Schema for validating array elements
 */
innerType: Schema | undefined;

/**
 * Validate exact array length
 * @param length - Required array length
 * @param message - Custom error message
 * @returns New schema with length constraint
 */
length(length: number, message?: string): ArraySchema;

/**
 * Validate minimum array length
 * @param min - Minimum allowed length
 * @param message - Custom error message
 * @returns New schema with minimum length constraint
 */
min(min: number, message?: string): ArraySchema;

/**
 * Validate maximum array length
 * @param max - Maximum allowed length
 * @param message - Custom error message
 * @returns New schema with maximum length constraint
 */
max(max: number, message?: string): ArraySchema;

/**
 * Ensure array exists (converts null to empty array)
 * @returns New schema with null handling
 */
ensure(): ArraySchema;

/**
 * Remove falsy or rejected values from array
 * @param rejector - Function to test which values to remove
 * @returns New schema with compaction transformation
 */
compact(rejector?: (value: T) => boolean): ArraySchema<NonNullable<T>>;

/**
 * Parse JSON string to array during validation
 * @returns New schema with JSON parsing
 */
json(): ArraySchema;

Tuple Schema

Specialized schema for tuple validation with fixed element positions and types.

/**
 * Array of schemas for each tuple position
 */
spec: {
  types: Schema[];
};

Schema Classes

The actual schema class definitions that provide the implementation for all schema functionality.

/**
 * Base schema class - all other schemas extend this
 */
abstract class Schema<T = any, C = any, F = any, D = any> {
  // Core validation and casting methods inherited by all schemas
  cast(value: any, options?: CastOptions<C>): T;
  validate(value: any, options?: ValidateOptions<C>): Promise<T>;
  validateSync(value: any, options?: ValidateOptions<C>): T;
  isValid(value: any, options?: ValidateOptions<C>): Promise<boolean>;
  isValidSync(value: any, options?: ValidateOptions<C>): boolean;
  isType(value: any): value is T;
}

/**
 * Schema for validating any type of value
 */
class MixedSchema<T = any> extends Schema<T> {}

/**
 * Schema for validating string values
 */
class StringSchema extends Schema<string> {}

/**
 * Schema for validating number values
 */
class NumberSchema extends Schema<number> {}

/**
 * Schema for validating boolean values
 */
class BooleanSchema extends Schema<boolean> {}

/**
 * Schema for validating Date objects
 */
class DateSchema extends Schema<Date> {}

/**
 * Schema for validating object structures
 */
class ObjectSchema<T extends ObjectShape = {}> extends Schema<T> {}

/**
 * Schema for validating arrays
 */
class ArraySchema<T = any> extends Schema<T[]> {}

/**
 * Schema for validating tuples with fixed element types
 */
class TupleSchema<T extends readonly [...any[]]> extends Schema<T> {}

Install with Tessl CLI

npx tessl i tessl/npm-yup

docs

index.md

schema-types.md

utilities.md

validation.md

tile.json