tcomb-validation

3.4.1 · active · verified Sun Apr 19

tcomb-validation is a general-purpose JavaScript validation library built upon the tcomb type combinator library. It provides a concise yet expressive syntax for validating various data structures, including native types, refinements, objects, lists, tuples, enums, unions, dicts, and intersections, with arbitrary nesting levels. The library offers detailed information on failed validations, making it a lightweight alternative to JSON Schema for validating domain models. The current stable version is 3.4.1, with releases typically addressing bug fixes and minor features, often in conjunction with its `tcomb` dependency. A key differentiator is its direct reuse of `tcomb` type definitions for validation, streamlining development when `tcomb` is already used for runtime type checking or domain modeling. It ships with TypeScript definitions, ensuring good type safety for modern JavaScript and TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define complex types using `tcomb`, then use `tcomb-validation`'s `validate` function to check both valid and invalid data, including strict validation and error introspection.

import * as t from 'tcomb';
import { validate } from 'tcomb-validation';

// Define a type using tcomb
const UserName = t.refinement(t.String, (s) => s.length > 3 && s.length < 20, 'UserName');

// Define a struct (object type)
const User = t.struct({
  id: t.Number,
  name: UserName,
  email: t.maybe(t.String) // optional email
}, 'User');

// Validate a valid object
const validUser = { id: 1, name: 'JohnDoe', email: 'john.doe@example.com' };
let result = validate(validUser, User);
console.log('Valid user result:', result.isValid()); // true

// Validate an invalid object
const invalidUser = { id: 'a', name: 'Jo', age: 30 }; // id wrong type, name too short, extra prop
result = validate(invalidUser, User, { strict: true }); // strict mode to disallow extra props
console.log('Invalid user result:', result.isValid()); // false
console.log('First error:', result.firstError()?.message);

// Inspect all errors
result.errors.forEach(error => {
  console.log(`Path: ${error.path.join('.')}, Value: ${error.value}, Message: ${error.message}`);
});
/* Expected output for invalidUser (may vary slightly based on tcomb-validation version):
   Path: id, Value: a, Message: Invalid value "a" supplied to Number
   Path: name, Value: Jo, Message: Invalid value "Jo" supplied to UserName
   Path: age, Value: 30, Message: Invalid key "age" supplied to User
*/

view raw JSON →