or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array-object-validation.mdcommon-decorators.mdcore-validation.mdcustom-validation-schema.mdindex.mdnumber-date-validation.mdstring-validation.mdtype-validation.md
tile.json

core-validation.mddocs/

Core Validation

Core validation functions provide the primary API for validating objects using decorators or programmatic schemas. These functions support both synchronous and asynchronous validation with comprehensive error reporting.

Capabilities

Validate Function

Validates objects using decorators applied to class properties or named validation schemas.

/**
 * Validates given object using decorators applied to the object's class
 * @param object - Object instance to validate
 * @param validatorOptions - Optional validation configuration
 * @returns Promise resolving to array of ValidationError objects
 */
function validate(object: object, validatorOptions?: ValidatorOptions): Promise<ValidationError[]>;

/**
 * Validates given object using a named validation schema
 * @param schemaName - Name of registered validation schema
 * @param object - Object to validate against schema
 * @param validatorOptions - Optional validation configuration
 * @returns Promise resolving to array of ValidationError objects
 */
function validate(schemaName: string, object: object, validatorOptions?: ValidatorOptions): Promise<ValidationError[]>;

Usage Examples:

import { validate, IsEmail, IsNotEmpty } from "class-validator";

class User {
  @IsNotEmpty()
  name: string;
  
  @IsEmail()
  email: string;
}

// Validate using decorators
const user = new User();
user.name = "";
user.email = "invalid-email";

const errors = await validate(user);
if (errors.length > 0) {
  errors.forEach(error => {
    console.log(`${error.property}: ${Object.values(error.constraints || {}).join(', ')}`);
  });
}

// Validate using named schema
const schemaErrors = await validate("userSchema", user);

ValidateOrReject Function

Validates objects and throws a ValidationError if validation fails, providing a promise-based error handling approach.

/**
 * Validates object and throws ValidationError on failure
 * @param object - Object instance to validate
 * @param validatorOptions - Optional validation configuration
 * @throws ValidationError - If validation fails
 * @returns Promise<void> - Resolves if validation succeeds
 */
function validateOrReject(object: object, validatorOptions?: ValidatorOptions): Promise<void>;

/**
 * Validates object using schema and throws ValidationError on failure
 * @param schemaName - Name of registered validation schema
 * @param object - Object to validate against schema
 * @param validatorOptions - Optional validation configuration
 * @throws ValidationError - If validation fails
 * @returns Promise<void> - Resolves if validation succeeds
 */
function validateOrReject(schemaName: string, object: object, validatorOptions?: ValidatorOptions): Promise<void>;

Usage Examples:

import { validateOrReject, IsEmail, IsNotEmpty } from "class-validator";

class User {
  @IsNotEmpty()
  name: string;
  
  @IsEmail()
  email: string;
}

const user = new User();
user.name = "John";
user.email = "john@example.com";

try {
  await validateOrReject(user);
  console.log("Validation passed!");
} catch (errors) {
  // errors is an array of ValidationError objects
  console.log("Validation failed:", errors);
}

ValidateSync Function

Performs synchronous validation, completely ignoring any asynchronous validators. Useful for scenarios where immediate validation results are needed.

/**
 * Validates object synchronously (ignores async validators)
 * @param object - Object instance to validate
 * @param validatorOptions - Optional validation configuration
 * @returns Array of ValidationError objects
 */
function validateSync(object: object, validatorOptions?: ValidatorOptions): ValidationError[];

/**
 * Validates object using schema synchronously (ignores async validators)
 * @param schemaName - Name of registered validation schema
 * @param object - Object to validate against schema
 * @param validatorOptions - Optional validation configuration
 * @returns Array of ValidationError objects
 */
function validateSync(schemaName: string, object: object, validatorOptions?: ValidatorOptions): ValidationError[];

Usage Examples:

import { validateSync, IsEmail, IsNotEmpty } from "class-validator";

class User {
  @IsNotEmpty()
  name: string;
  
  @IsEmail()
  email: string;
}

const user = new User();
user.name = "";
user.email = "invalid";

// Immediate synchronous validation
const errors = validateSync(user);
if (errors.length > 0) {
  console.log("Immediate validation failed:", errors);
}

RegisterSchema Function

Registers a validation schema for use with schema-based validation, providing an alternative to decorator-based validation.

/**
 * Registers a validation schema for schema-based validation
 * @param schema - ValidationSchema object containing validation rules
 */
function registerSchema(schema: ValidationSchema): void;

Usage Examples:

import { registerSchema, validate } from "class-validator";

// Register a schema
registerSchema({
  name: "userSchema",
  properties: {
    name: [
      { type: "isNotEmpty" },
      { type: "length", constraints: [2, 20] }
    ],
    email: [
      { type: "isEmail" }
    ]
  }
});

// Use the schema for validation
const user = { name: "", email: "invalid" };
const errors = await validate("userSchema", user);

Validator Class

The core validation engine that processes objects and schemas. Typically accessed through the convenience functions above, but available for direct use.

/**
 * Core validator class for processing validation rules
 */
class Validator {
  /**
   * Validates object using decorators or named schema
   */
  validate(object: object, validatorOptions?: ValidatorOptions): Promise<ValidationError[]>;
  validate(schemaName: string, object: object, validatorOptions?: ValidatorOptions): Promise<ValidationError[]>;
  
  /**
   * Validates and throws on failure
   */
  validateOrReject(object: object, validatorOptions?: ValidatorOptions): Promise<void>;
  validateOrReject(schemaName: string, object: object, validatorOptions?: ValidatorOptions): Promise<void>;
  
  /**
   * Synchronous validation
   */
  validateSync(object: object, validatorOptions?: ValidatorOptions): ValidationError[];
  validateSync(schemaName: string, object: object, validatorOptions?: ValidatorOptions): ValidationError[];
}

Validation Configuration

ValidatorOptions Interface

Comprehensive configuration options for customizing validation behavior.

interface ValidatorOptions {
  /** Skip validation for undefined properties (default: false) */
  skipUndefinedProperties?: boolean;
  
  /** Skip validation for null properties (default: false) */
  skipNullProperties?: boolean;
  
  /** Skip validation for null and undefined properties (default: false) */
  skipMissingProperties?: boolean;
  
  /** Strip properties without decorators from validated object (default: false) */
  whitelist?: boolean;
  
  /** Throw error if non-whitelisted properties exist (default: false) */
  forbidNonWhitelisted?: boolean;
  
  /** Validation groups to validate (default: undefined - all groups) */
  groups?: string[];
  
  /** Ignore decorators with groups if no groups specified (default: false) */
  strictGroups?: boolean;
  
  /** Don't use default validation error messages (default: false) */
  dismissDefaultMessages?: boolean;
  
  /** Control what gets included in ValidationError objects */
  validationError?: {
    /** Include target object in error (default: true) */
    target?: boolean;
    /** Include validated value in error (default: true) */
    value?: boolean;
  };
  
  /** Fail validation for objects unknown to class-validator (default: false) */
  forbidUnknownValues?: boolean;
  
  /** Stop validation on first error (default: false) */
  stopAtFirstError?: boolean;
  
  /** Default value for 'always' option on decorators (default: false) */
  always?: boolean;
  
  /** Print debug messages during validation (default: false) */
  enableDebugMessages?: boolean;
}

Error Handling

ValidationError Class

Detailed error information returned by validation functions.

/**
 * Validation error containing detailed failure information
 */
class ValidationError {
  /** Object that was validated */
  target?: object;
  
  /** Property name that failed validation */
  property: string;
  
  /** Value that failed validation */
  value?: any;
  
  /** Map of constraint names to error messages */
  constraints?: {[type: string]: string};
  
  /** Nested validation errors for object properties */
  children?: ValidationError[];
  
  /** Transient validation context data */
  contexts?: {[type: string]: any};
  
  /**
   * Format error as string representation
   * @param shouldDecorate - Whether to add decorative formatting
   * @param hasParent - Whether this error has a parent error
   * @param parentPath - Path from parent error
   * @param showConstraintMessages - Whether to show constraint messages
   * @returns Formatted error string
   */
  toString(shouldDecorate?: boolean, hasParent?: boolean, parentPath?: string, showConstraintMessages?: boolean): string;
}

Usage Examples:

import { validate, ValidationError } from "class-validator";

const errors: ValidationError[] = await validate(invalidObject);

errors.forEach(error => {
  console.log(`Property: ${error.property}`);
  console.log(`Value: ${error.value}`);
  console.log(`Constraints: ${JSON.stringify(error.constraints)}`);
  
  // Handle nested errors
  if (error.children && error.children.length > 0) {
    error.children.forEach(child => {
      console.log(`  Nested error: ${child.property} - ${child.constraints}`);
    });
  }
});

Validation Utilities

ValidationTypes Class

Utility class containing validation type constants used internally by the validation system.

/**
 * Validation types for internal validation system categorization
 */
class ValidationTypes {
  /** Custom validation type */
  static CUSTOM_VALIDATION: string;
  
  /** Nested object validation */
  static NESTED_VALIDATION: string;
  
  /** Promise-based validation */
  static PROMISE_VALIDATION: string;
  
  /** Conditional validation */
  static CONDITIONAL_VALIDATION: string;
  
  /** Whitelist validation */
  static WHITELIST: string;
  
  /** Defined value validation */
  static IS_DEFINED: string;
  
  /**
   * Checks if validation type is valid
   * @param type - Validation type string to check
   * @returns Whether the type is a valid validation type
   */
  static isValid(type: string): boolean;
}

Container System

The container system provides dependency injection support for custom validators and validation constraints.

Container Functions

/**
 * Sets container to be used by class-validator for dependency injection
 * @param iocContainer - IoC container that implements get() method
 * @param options - Container configuration options
 */
function useContainer(iocContainer: { get(someClass: any): any }, options?: UseContainerOptions): void;

/**
 * Gets instance from the IoC container used by class-validator
 * @param someClass - Class constructor to get instance for
 * @returns Instance from container or new instance if no container set
 */
function getFromContainer<T>(someClass: { new (...args: any[]): T } | Function): T;

/**
 * Container configuration options
 */
interface UseContainerOptions {
  /** Use default container if given container returns nothing (default: false) */
  fallback?: boolean;
  
  /** Use default container if given container throws error (default: false) */
  fallbackOnErrors?: boolean;
}

Usage Examples:

import { useContainer, ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
import { Container } from "typedi"; // Example IoC container

// Set up container integration
useContainer(Container, { fallback: true });

@ValidatorConstraint({ name: "customText", async: false })
export class CustomTextLengthConstraint implements ValidatorConstraintInterface {
  // Container will inject dependencies here
  constructor(private configService: ConfigService) {}

  validate(text: string) {
    return text.length <= this.configService.getMaxLength();
  }

  defaultMessage() {
    return "Text is too long";
  }
}