Tiny Validator for JSON Schema v4
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
-
RangeError: Maximum call stack size exceeded
cause Attempting to validate a JavaScript object with circular references without enabling recursive checking.fixPass `true` as the third argument to the validation method: `tv4.validate(data, schema, true);` or `tv4.validateResult(data, schema, true);`. -
{ valid: false, error: { ... }, missing: [] } where error seems incorrect or refers to a previous validation.cause Using `tv4.validate(data, schema)` in an environment where multiple validations might occur concurrently, leading to the global `tv4.error` property being overwritten.fixSwitch to `tv4.validateResult(data, schema)` which returns a self-contained result object, preventing global state conflicts. -
Validation passes (returns `true`) but some schemas referenced by `$ref` are not actually validated.
cause The referenced schemas were not added to `tv4` using `tv4.addSchema(url, schema)`, and the validation was synchronous. `tv4.missing` will indicate which schemas were not found.fixEnsure all referenced schemas are pre-loaded using `tv4.addSchema(url, schema)` before validation. Alternatively, if asynchronous fetching is set up, ensure it's properly configured and awaited. -
JSON data contains an extra field not defined in the schema, but validation still passes.
cause By default, `tv4` ignores properties not explicitly defined in the schema.fixSet `tv4.banUnknownProperties = true;` globally or add `"additionalProperties": false` to your schema to disallow undeclared properties.
Warnings
- breaking tv4 is no longer actively maintained. Its last release was in 2015, and it strictly supports only JSON Schema Draft v4. It does not support newer drafts (like Draft 6, 7, 2019-09, or 2020-12), meaning schemas written for modern JSON Schema specifications will not validate correctly.
- gotcha The default `tv4.validate` method returns a boolean and stores the last validation error in `tv4.error` and missing schemas in `tv4.missing`. These are global properties, making `tv4.validate` unsafe for concurrent or multi-threaded environments, as validation results can be overwritten.
- gotcha By default, `tv4` stops validation on the first encountered error. This means `tv4.validate` and `tv4.validateResult` will only report one error at a time.
- gotcha Validation of cyclical JavaScript objects (objects that reference themselves, which are not valid JSON but can exist in JavaScript) can lead to 'too much recursion' errors or script hangs.
- gotcha By default, `tv4` ignores properties in your data that are not defined in the schema. This can lead to unexpected behavior if you intend for unknown properties to cause validation failure.
- gotcha Asynchronous validation, which allows `tv4` to fetch missing schemas dynamically, is not built-in and requires an external file (`tv4.async-jquery.js`) that currently has a dependency on jQuery.
Install
-
npm install tv4 -
yarn add tv4 -
pnpm add tv4
Imports
- tv4
import tv4 from 'tv4';
const tv4 = require('tv4'); - validate
import { validate } from 'tv4'; const isValid = validate(data, schema);const tv4 = require('tv4'); const isValid = tv4.validate(data, schema); - tv4.addSchema
import { addSchema } from 'tv4';const tv4 = require('tv4'); tv4.addSchema(url, schema);
Quickstart
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);
}