{"id":13783910,"url":"https://github.com/ericgj/json-schema-valid","last_synced_at":"2025-03-05T11:27:24.362Z","repository":{"id":11023697,"uuid":"13353803","full_name":"ericgj/json-schema-valid","owner":"ericgj","description":"modular JSON Schema validator","archived":false,"fork":false,"pushed_at":"2014-01-30T17:28:22.000Z","size":461,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-16T16:42:28.391Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ericgj.png","metadata":{"files":{"readme":"Readme.md","changelog":"History.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-10-05T22:42:59.000Z","updated_at":"2022-01-07T10:27:41.000Z","dependencies_parsed_at":"2022-09-02T04:26:38.370Z","dependency_job_id":null,"html_url":"https://github.com/ericgj/json-schema-valid","commit_stats":null,"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ericgj%2Fjson-schema-valid","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ericgj%2Fjson-schema-valid/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ericgj%2Fjson-schema-valid/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ericgj%2Fjson-schema-valid/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ericgj","download_url":"https://codeload.github.com/ericgj/json-schema-valid/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242017413,"owners_count":20058424,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T19:00:32.908Z","updated_at":"2025-03-05T11:27:24.342Z","avatar_url":"https://github.com/ericgj.png","language":"JavaScript","funding_links":[],"categories":["Who Uses the Test Suite"],"sub_categories":["JavaScript"],"readme":"\n# json-schema-valid\n\n  **Please note this library is not ready for production use.**\n\n  A modular javascript [JSON Schema v4][jsonschema] validator.\n  \n  Suitable for standalone use (see \"validator object\" mode below),\n  or together with other components to handle dereferencing,\n  correlation, hypermedia, etc.\n\n  If you are looking for a (mostly) complete JSON Schema toolkit,\n  see [json-schema-suite][suite] which bundles the components\n  together.\n\n\n## Installation\n\n[component][component]:\n\n    $ component install ericgj/json-schema-valid\n\nnpm:\n\n    $ npm install json-schema-valid-component\n\n## Examples\n\n  There are two basic modes: as a _validator object_, and as a _Correlation\n  binding_.\n\n  __Validator object__:\n  \n```javascript\n  var Validator = require('json-schema-valid')\n\n  var validator = new Validator()\n\n  // if schema has already been parsed\n  var valid = validator.validate(schema,instance);\n  \n  // if raw schema object\n  var valid = validator.validateRaw(rawSchema,instance);\n  \n  // checking state\n  validator.valid();           // boolean\n  validator.error();           // validation errors wrapped in an Error object\n  validator.errorTrace();      // array of error messages with indented levels\n  validator.assertionTrace();  // array of all assertions made on instance\n  validator.errorTree();       // tree structure of validation errors \n  validator.assertionTree();   // tree structure of all assertions\n\n```\n\n  __Correlation binding__:\n\n```javascript\n\n  var core = require('json-schema-core')\n    , Schema = core.Schema\n    , plugin = require('json-schema-valid')\n   \n  // attach plugin to Schema \n  Schema.use(plugin);\n\n  // now once you have a correlation, you can call validate() on it\n  var valid = correlation.validate();\n\n  // handling validation errors\n  correlation.on('error', function(err){\n    console.log('validation error: %o', err);\n  }\n\n  // subschema for given instance property\n  // resolving valid combination conditions (allOf, anyOf, oneOf)\n  var subschema = correlation.subschema('foo');\n\n  // resolved URI-template links, including for valid combination conditions\n  var links = correlation.links();\n\n  // coerced instance (i.e., type and defaults applied to copy of instance)\n  var coerced = correlation.coerce().instance;\n\n```\n\nNote that \"raw\" assertion data (`assertionTree()`, `assertionTrace()`) are \n_not_ currently available using the 'correlation binding' mode. The error\ntrace and tree are available through the error object emitted after failed \nvalidation (see below, \"Events\").\n\n\n## Formats\n\nThe following JSON Schema v3 format validations are built-in:\n\n  - `datetime` (ISO 8601)\n  - `date` (YYYY-MM-DD)\n  - `time` (HH:MM:SS)\n  - `utc` (milliseconds since 1970-01-01 00:00 UTC)\n  - `regex`\n  - `phone`\n  - `uri`\n  - `email`\n\nIn addition, the following custom formats are available:\n\n### js-function\n\nA custom format `js-function` is available which allows \nserialization of simple javascript expressions (using the \n[to-function][to-func] library).\n\nYou can use this for custom validation involving instance values.\nFor instance, the rule \"x must be greater than 2 times y\" can be\nexpressed in the schema as:\n\n  ```json\n  {\n    \"type\": \"object\",\n    \"format\": \"js-function\",\n    \"js-function\": \"x \u003e 2 * _.y\",\n    \"required\": [\"x\",\"y\"],\n    \"properties\": {\n      \"x\": { \"type\": \"number\" },\n      \"y\": { \"type\": \"number\" }\n    }\n  }\n  ```\n\nThe expression is specified as a string (or object) value of the \"js-function\"\nkey.\n\n(Note the [to-function][to-func] library also allows \"query-object\" style \nconditions as well as strings, see its documentation for details.)\n\nOf course, this custom format will be ignored by other implementations, so\nif you are concerned about portability, you may wish to avoid using this \nformat. \n\nNote however there is no current standard for custom validation involving\nseveral instance values (a typical use-case for js-function). The JSON Schema \nv5 spec will have such a standard for simple cases (see \n[draft proposals][v5-proposals]).\n\n### non-blank\n\nThis format allows more expressive error messages for cases where empty-string\nvalues are considered *missing*. Instead of using `{ \"minLength\": 1 }` and\ngetting error messages like _is less than the minimum length_, you can use\n`{ \"format\": \"non-blank\" }` and get _is missing_. Essentially, this format\nconsiders both *null* and *zero-length string* values to be *missing*.\n\n### Using custom formats\n\nTo use the custom formats listed above:\n\n  ```javascript \n  Validator.addFormat('js-function', \n    require('ericgj-json-schema-valid/format/js-function')\n  );\n  ```\n\nTo use your own format: \n\n  ```javascript\n  Validator.addFormat('my-format', myFormatFunction);\n  ```\n\n## API\n\n### Validator.prototype.validate( schema:Schema, instance:Object, [callback:Function] )\n\n  Validate given instance against given schema.  Takes optional callback\n  function. Callback receives array of valid schemas (i.e., the root-level\n  schema plus any schemas valid through combination conditions). Callback\n  is only run if validation succeeds (valid).\n\n### Validator.prototype.validateRaw( schema:Object, instance:Object, [callback:Function] )\n\n  Validate given instance against given raw schema (parsing schema first).\n\n### Validator.prototype.valid()\n\n  Result of the last `validate()` call (boolean).\n\n### Validator.prototype.error()\n\n  If the last `validate()` call returned false (invalid), then returns an error \n  object that wraps the error state:\n    \n  - `message` is the top-level error message for the instance;\n  - `trace` is an array of error messages for invalid branches (see \n    `errorTrace`);\n  - `tree` is a tree-structure of error state for all failed\n    validation conditions (see `errorTree`).\n\n### Validator.prototype.errorTrace()\n\n  If the last `validate()` call returned false (invalid), then returns an array\n  of error messages for invalid branches, indented according to context level.\n\n### Validator.prototype.errorTree()\n\n  If the last `validate()` call returned false (invalid), then returns a tree\n  structure of all failed assertions on invalid branches:\n\n  - `assertions()` returns an array of failed assertions on the current\n    branch. Each assertion object contains, besides an error message, schema\n    and instance state and other info.\n  - `branches()` returns an array of branches (sub-contexts), each of which\n    has its own assertions and branches.\n\n  This structure can be used for custom error handling/messaging.\n\n### Validator.prototype.assertionTrace()\n\n  Returns array of assertion messages for all validated branches of the last\n  `validate()` call (regardless of whether valid or invalid).\n\n### Validator.prototype.assertionTree()\n\n  Returns tree structure of all assertions on all validated branches of the \n  last `validate()` call (regardless of whether valid or invalid).\n\n### Validator.addType( key:String, validator:Function )\n\n  Add custom validation function. See `type/*.js` for examples of how\n  to write validation functions.\n\n### Validator.addFormat( format:String, validator:Function|Regexp )\n\n  Add custom format validation function or regular expression to match.\n  Note specifying a regular expression here is essentially like having\n  named schema `pattern` properties.\n\n### Correlation#validate( [callback:Function] )\n\n  Validate correlation instance against correlation schema. \n\n### Correlation#resolveLinks()\n\n  Validate, and return links merged from all valid schemas, if valid.\n  \n  Intended to be used with the [hyperschema plugin][hyper], to provide\n  `links()`, `rel()`, etc. methods to the correlation, when combination\n  conditions are specified. If the hyperschema plugin is not used, this\n  method returns undefined. \n\n  See `test/tests.js` for usage examples.\n\n### Correlation#subschema( property:String )\n\n  Validate, and get the subschema describing the given instance property.\n  If multiple subschemas are valid, the subschema is normalized as a \n  single allOf condition.\n\n  Intended to be used as the basis for `correlation.getPath()` for \n  co-traversing the schema and instance, when combination conditions are\n  specified.\n\n  See `test/tests.js` for usage examples. \n\n### Correlation#coerce()\n\n  Validate, and coerces instance (applies type and default) according to:\n    \n  1.  the first valid schema that specifies either `type` or `default` or \n      both;\n  2.  the \"top-level schema\", otherwise, whether instance is valid or\n      invalid.\n\n\n  Note that the ordering of valid schemas cannot be relied on, so it is\n  recommended that either the top-level schema specify type and/or default, or\n  _only one_ combination schema specify these.\n\n## Events\n\n### Correlation#emit('error', fn[err])\n\n  On validation failure, the correlation emits 'error' with the error.\n  `err.message` is the first \"top-level\" error. `err.trace` is the error trace\n  (equivalent of `validator.errorTrace()`). `err.tree` is the error tree\n  (equivalent of `validator.errorTree()`).\n\n\n## Running tests\n\nIn browser:\n\n  1. Run `make` to generate JSON Schema test suite files and build the \n     component.\n\n  2. Browse the file `test/index.html`. Tests are run via in-browser mocha.\n\nIn node:\n\n  1. Run `make node` to generate JSON Schema test suite files.\n\n  2. `npm test`\n\n\n## A note on dereferencing\n\n  Dereferencing schemas is _not_ implemented here. It is assumed that schemas\n  with JSON references (`$ref`) will have already been dereferenced, making\n  use of an http client library. See for example [json-schema-agent][agent],\n  which provides both correlation (via HTTP headers) and schema dereferencing.\n\n  My view is that dereferencing necessarily involves external resources\n  (the HTTP stack) and thus should be cleanly separated from validation.\n\n  However, if you _know_ that your schema files will only have internal\n  (fragment) references, it is possible to dereference without loading\n  external resources (what the spec refers to as _inline_ vs. canonical\n  dereferencing). For convenience, in the future I will add inline\n  dereferencing to [json-schema-core][core]. For now, the underlying Schema\n  data structure does provide an interface for manipulating references,\n  so it is also possible to roll your own inline dereferencing.\n\n\n## TODO\n\n  - \u003cdel\u003eadd common format validators\u003c/del\u003e\n  - make error data compatible with [tv4][tv4] errors\n  - \u003cdel\u003econsider emitting schema-level errors or 'error trees' / rework internal\n    Context objects\u003c/del\u003e\n  - more complete walk-through of how to use with json-schema-hyper,\n    json-schema-agent, etc. (add to json-schema-suite).\n  - bower \u003cdel\u003eand npm\u003c/del\u003e installation\n\n## Acknowledgements\n\n  The validation logic used in this library is about 90% cribbed from the\n  [geraintluff/tv4][tv4] javascript reference implementation. Thanks for\n  that Geraint :beers: , and thanks equally for your always-excellent\n  documentation of how JSON Schema is supposed to work, both in the specs\n  and on the [json-schema email list][group].\n\n  Regular expression for `datetime` format thanks to \n  [Cameron Brooks][regex-datetime].\n  \n  Regular expression for `uri` format thanks to \n  [\"Yaffle\"][regex-uri].\n  \n  Regular expression for `email` format thanks to \n  [Jan Goyvaerts, regular-expressions.info][regex-email].\n  \n## License\n\n  MIT\n\n\n[component]: https://github.com/component/component\n[jsonschema]: http://json-schema.org\n[core]: https://github.com/ericgj/json-schema-core\n[hyper]: https://github.com/ericgj/json-schema-hyper\n[agent]: https://github.com/ericgj/json-schema-agent\n[suite]: https://github.com/ericgj/json-schema-suite\n[emitter]: https://github.com/component/emitter\n[tv4]: https://github.com/geraintluff/tv4\n[group]: https://groups.google.com/forum/#!forum/json-schema\n[v5-proposals]: https://github.com/json-schema/json-schema/wiki/v5-Proposals\n[to-func]: https://github.com/component/to-function\n[regex-datetime]: http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/\n[regex-uri]: https://gist.github.com/1088850\n[regex-email]: http://www.regular-expressions.info/email.html\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fericgj%2Fjson-schema-valid","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fericgj%2Fjson-schema-valid","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fericgj%2Fjson-schema-valid/lists"}