Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

djv

korzio254.1kMIT2.1.4TypeScript support: definitely-typed

dynamic json-schema validator

json-schema, json, schema, validator, validate

readme

Build Status Join the chat at https://gitter.im/korzio/djv

djv

Dynamic JSON-Schema Validator

Official Documentation

Current package supports JSON-Schema v6 and v4. It contains utils to validate objects against schemas. This is a part of djv packages aimed to work with json-schema.

  • djv validate object against schemas
  • djvi instantiate objects by schema definition
  • jvu utilities for declarative, FP usage
  • @djv/draft-04 environment updates to support draft-04

Any contributions are welcome. Check the contribution guide. Since version 1.2.0 djv package supports draft-06. Version 2.0.0 makes draft-06 the default schema version. To use other versions check the environment section.

Table of contents

Install

npm install djv

or

<script src="djv.js"></script>

There are 2 versions of validator

  • ./lib/djv.js a default one, not uglified and not transpiled
  • ./djv.js a built one with a webpack, babel and uglify (preferable for frontend)

Usage

const env = new djv();
const jsonSchema = {
  "common": {
    "properties": {
      "type": {
        "enum": ["common"]
      }
    },
    "required": [
      "type"
    ]
  }
};

// Use `addSchema` to add json-schema
env.addSchema('test', jsonSchema);
env.validate('test#/common', { type: 'common' });
// => undefined

env.validate('test#/common', { type: 'custom' });
// => 'required: data'

API

Environment

To instantiate djv environment

const djv = require('djv');
const env = djv({
  version: 'draft-06', // use json-schema draft-06
  formats: { /*...*/ }, // custom formats @see #addFormat
  errorHandler: () => { /*...*/ }, // custom error handler, @see #setErrorHandler
});

To use a previous version of JSON-Schema draft, use a draft-04 plugin, specified in optionalDependencies of djv package.

const env = new djv({ version: 'draft-04' });

addSchema(name: string, schema: object?) -> resolved: object

Add a schema to a current djv environment,

env.addSchema('test', jsonSchema);
/* => {
  fn: function f0(data){...}
  name: 'test'
  schema: ...
} */

validate(name: string, object: object) -> error: string

Check if object is valid against the schema

env.validate('test#/common', { type: 'common' });
// => undefined

env.validate('test#/common', { type: 'custom' });
// => 'required: data'

where

  • name - schema path in current environment
  • object - object to validate
  • error - undefined if it is valid

removeSchema(name: string)

Remove a schema or the whole structure from the djv environment

env.removeSchema('test');

resolve(name: string?)

Resolve the name by existing environment

env.resolve('test');
// => { name: 'test', schema: {} }, fn: ... }

export(name: string?) -> state: object

Export the whole structure object from environment or resolved by a given name

env.export();
// => { test: { name: 'test', schema: {}, ... } }

where state is an internal structure or only resolved schema object

import(config: object)

Import all found structure objects to internal environment structure

env.import(config);

addFormat(name: string, formatter: string/function)

Add formatter to djv environment. When a string is passed it is interpreted as an expression which when returns true goes with an error, when returns false then a property is valid. When a function is passed it will be executed during schema compilation with a current schema and template helper arguments.

env.addFormat('UpperCase', '%s !== %s.toUpperCase()');
// or
env.addFormat('isOk', function(schema, tpl){
  return `!${schema.isOk}`;
});
env.validate('ok', 'valid') // => undefined if schema contains isOk property

setErrorHandler(errorHandler: function)

Specify custom error handler which will be used in generated functions when problem found. The function should return a string expression, which will be executed when generated validator function is executed. The simplist use case is the default one @see template/defaultErrorHandler

 function defaultErrorHandler(errorType) {
   return `return "${errorType}: ${tpl.data}";`;
 }

It returns an expression 'return ...', so the output is an error string.

djv({ errorHandler: () => 'return { error: true };' }) // => returns an object
djv({
  errorHandler(type) {
    return `errors.push({
      type: '${type}',
      schema: '${this.schema[this.schema.length - 1]}',
      data: '${this.data[this.data.length - 1]}'
    });`;
  }
});

When a custom error handler is used, the template body function adds a error variable inside a generated validator, which can be used to put error information. errorType is always passed to error handler function. Some validate utilities put extra argument, like f.e. currently processed property value. Inside the handler context is a templater instance, which contains this.schema, this.data paths arrays to identify validator position. @see test/index/setErrorHandler for more examples

useVersion(version: string, configure: function)

To customize environment provide a configure function which will update configuration for djv instance.

env.useVersion('draft-04')
// or
env.useVersion('custom', configure)

Configure will get internal properties as an argument. Check the @korzio/djv-draft-04 code.

exposed = {
  properties,
  keywords,
  validators,
  formats,
  keys,
  transformation,
}

!Important Modifying them will affect all djv instances in an application.

Tests

npm test

References

changelog

2.1.4 (2020-12-27)

Chores
  • npm: regenerate package lock (46bfdbe8)
  • code: Move clear decode function to outer scope (5e65fda4)

2.1.2 (2019-03-06)

Other Changes
  • Update package version to 2.1.2 #76 (9b40c9d5)
  • Fix required validator throwing on null values #75

2.1.1 (2018-09-04)

Other Changes

Add browser field

2.1.0 (2018-06-24)

New Features
  • error code [BREAKING CHANGE] Change default error handlers to output error objects instead of strings (#54)
Other Changes

2.0.0 (2017-10-10)

New Features
  • env [BREAKING CHANGE] Make schema v6 default #48 (bd1d4cae)
Documentation Changes
  • api Add auto-generated docs #48 (440ff67d)
  • site Add index documentation page #48 (cb4db59b)
  • env Add environment section to describe options (5e0e1a91)

1.2.0 (2017-09-25)

Documentation Changes
  • npm: Remove docs folder from npm files #51 (d5d2a8de)
  • readme: Update v6 support #51 (2ec9d7f0)
  • const: Add const documentation #51 (b7f0355d)
  • state:
  • todo: Add todo for draft-06 #41 (4fa64971)
  • contribute: Change tests debug description (b0d03069)
  • contributing:
  • release: Add table of contents, update release contributing #35 (2f69a166)
  • Update api docs, format utils (11cae181)
New Features
  • id: Add $id, examples keywords #44 (1ef4745f)
  • format: Add uri formats #44 (79802269)
  • validator:
  • validators: Add useVersion method to change environment version; Add exlusive maximum/minimum properties #44 (f57f9116)
Bug Fixes
  • test:
    • Add name json mock data to test environment #41 (c1d0e13b)
  • rename: Rename template resolve to link as in state #41 (34fc6e4d)
  • format: Add regex, fix uri formatters #44 (757397d7)
  • draft-06:
    • Move validators to patch environment #44 (9f7412bc)
    • Fix properties strict type check #44 (f663f7ba)
  • boolean: Fix transform default schema (69488621)
  • tests: Add isSchema, transformSchema utilities for boolean schema presentation #44 (cb48a2a1)
  • validator: Add not array required check #44 (83b01279)
Other Changes
  • state: Fix skip describe for jasmine #41 (52ffd0c7)
  • debug: Add console output if error is thrown (6b61a465)
  • Add draft-06 tests; Switch to json schema test package #44 (1a9ce7e7)
Refactors
  • files:
    • Clean code; Remove deprecated #51 (b815f6dc)
    • Clean code; Split utils to uri and schema; Move transforms to environment #51 (7c497fb5)
  • performance: Clean code; Change uri keys utils; Rewrite state resolution id algorithm to not use multiple functions calls #51 (1fe9339d)
  • state:
    • Clean code; Change cleanId to head #51 (465749a4)
    • Add draft-06 meta schema to tests; Add uriKeys variable to contain id/$id changes; Fix boolean schema descend resolution #41 (01b37316)
    • Move descend to state; Fix intermediate ids resolution #41 (ad70e8e7)
    • Fix uri utils regexps #41 (0df12100)
    • Fix ignore other properties in $ref schemas; Clean schemas stack after visit #41 (fe85a55b)
    • Add reference schema resolution; Add resolution by id #41 (64d9ba5e)
    • Simplify resolution; Rename descend utils #41 (c55f3af6)
  • validators:
    • Change hasOwnProperty usage; Add checks for boolean schemas #44 (af5fcc75)
Code Style Changes
  • state: Normalize if-else utils clauses #41 (b9b11e29)
Tests
  • properties: Add check for object type #44 (3fb8bcbb)

1.1.1 (2017-07-20)

Documentation Changes
  • contributing:
    • Add benchmark suite debug description (b0c05722)
    • Add contributing rules file (3a0db5b4)
  • Fix text (470ec0f0)
  • Change changelog package version (f7f44e88)
  • error handle: Fix example (9b7a5545)
New Features
  • webpack:
    • Add source maps, add manual test html, update docs #34 (40ecd525)
    • Update webpack #34 (73cfa621)
Bug Fixes
  • utils: Add type checking (038d89a7)
  • validators: Add required type object check (4970bc5e)
  • items: Add items is array check #29 (d13cdcd2)
  • test: Add latest suite tests (323c9a0d)
Refactors
  • state:
    • Handle circular self schema dependency (7bbefcc5)
    • Add resolution schema search (05307fcc)
    • Add iterate through fragment even it is not a fragment (068114c1)
    • Clean descent utils method (fd18b7d8)
    • Move descent outside of the state (3691b361)
    • Change domain to path usage in url resolution (856f1a52)
    • Add full uri check for resolution purpose (1bdf4e88)
    • Add experimental strategy to resolve state (fb9c5a96)
    • Change ascend method to solve parentSchema (e366f3dc)
    • Draft rename resolution scope (99aaea1e)
    • Add join path utility (8dc9cee2)

1.1.0 (2017-6-16)

New Features
  • error: Add ability to customize error handler #16 (3b6b69ee)
  • format: Add custom formatter for environment, unite generate and state in one file (3dd47aeb)
Bug Fixes
  • environment: Add clean id method #20 (b9bfc527)
  • state: Add deferred schema resolution for loop references #13 (b818df12)
Other Changes
  • readme: Add addFormat description #15 (7878ff95)
  • Add throw test; Change register draft (dd6662d9)
  • Add documentation for utilties #13 (867fe41b)
  • Refactor coupled generate (495d8ac0)
  • Move resolve to state prototype (bc1167d9)
  • Restructure utils, move to folder, split into files (2de156de)
  • Refactor inner toFunction, move to generate (a9b7f6fe)
  • Separate state class (192fdfd2)
  • Add generated functions entries cache (8a84ece3)
  • Clean visited state (44fa0d45)
  • Move static generate functions to utils (8acc4059)
Refactors
  • validators: Separate property and format validators #15 (910f7674)
  • state:
    • Add generate method to state #13 (ba6d18e9)
    • Make state use environment resolved object #13 (79dce9db)
Code Style Changes
  • utilities: Clean utilities format #14 (6c994916)
  • template:
    • Rename fn to tpl as in other places #15 (85217a25)
    • Rename template instance to tpl #13 (def56c91)
  • lint: Temporary fix global require with lint comment (489717fe)
  • comment: Uncomment try catch for tests (68db5919)