Tiny Validator for JSON Schema v4

1.3.0 · abandoned · verified Sun Apr 19

tv4 is an abandoned JavaScript library designed for validating data against JSON Schema Draft v4 exclusively. Its latest release, version 1.3.0, was published in August 2015, with no subsequent updates or active maintenance. The library differentiates itself by offering synchronous, single-error validation by default, with optional methods for collecting multiple errors (`validateMultiple`) or a structured result object (`validateResult`) to better support multi-threaded environments where global state (`tv4.error`, `tv4.missing`) is problematic. It also supports `$ref` for referencing external schemas and has an optional mechanism for handling cyclical JavaScript objects. Due to its strict adherence to Draft v4 and lack of updates, it does not support newer JSON Schema drafts (like Draft 6, 7, 2019-09, or 2020-12) and is not recommended for new projects requiring modern schema features or active support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic synchronous JSON Schema Draft v4 validation, including how to handle validation results and errors, disallow additional properties, and use the `validateResult` method for safer error handling in shared environments.

const tv4 = require('tv4');

// Define your data to be validated
const data = {
  name: 'John Doe',
  age: 30,
  email: 'john.doe@example.com',
  occupation: 'Software Engineer'
};

// Define your JSON Schema Draft v4
const schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "age", "email"],
  "additionalProperties": false // Disallow unknown properties
};

// Perform validation
const result = tv4.validateResult(data, schema, true); // Use validateResult for structured output and checkRecursive

if (!result.valid) {
  console.error('Validation failed!');
  console.error('Error:', result.error);
  if (result.missing && result.missing.length > 0) {
    console.warn('Missing schemas:', result.missing);
  }
} else {
  console.log('Validation successful!');
}

// Example with an invalid data
const invalidData = { name: 'Jane Doe', age: 'twenty', email: 'invalid-email' };
const invalidResult = tv4.validateResult(invalidData, schema);
if (!invalidResult.valid) {
  console.error('\nValidation failed for invalid data:');
  console.error('Error:', invalidResult.error);
}

view raw JSON →