{"name":"z-schema","version":"3.4.2","description":"JSON schema validator","homepage":"https://github.com/zaggino/z-schema","authors":["Martin Zagora <zaggino@gmail.com>"],"license":"MIT","keywords":["JSON","Schema","Validator"],"repository":{"type":"git","url":"https://github.com/zaggino/z-schema.git"},"bugs":{"url":"https://github.com/zaggino/z-schema/issues"},"main":"src/ZSchema.js","bin":{"z-schema":"./bin/z-schema"},"files":["bin","src","dist","LICENSE","README.md"],"scripts":{"prepublish":"grunt","test":"grunt test"},"testling":{"scripts":["test/lib/jasmine-2.0.1/jasmine.js","test/lib/jasmine-2.0.1/jasmine-html.js","test/lib/jasmine-2.0.1/boot.js","test/lib/jasmine-2.0.1/tap_reporter.js","test/Runner.js","dist/ZSchema-browser-min.js","dist/ZSchema-browser-test.js"],"browsers":["iexplore/9..latest","chrome/4","chrome/28..latest","firefox/3.5","firefox/23..latest","safari/5.1..latest","opera/12..latest","iphone/6..latest","ipad/6..latest","android-browser/4.2..latest"]},"devDependencies":{"coveralls":"latest","grunt":"latest","grunt-browserify":"~3.2.1","grunt-contrib-jasmine":"latest","grunt-contrib-jshint":"latest","grunt-contrib-uglify":"latest","grunt-jasmine-node":"latest","grunt-jasmine-node-coverage":"latest","grunt-jscs":"latest","grunt-lineending":"latest","jasmine-node":"latest","jasmine-reporters":"latest","remapify":"latest"},"dependencies":{"commander":"^2.6.0","request":"^2.53.0"},"gitHead":"7c1d07e8ada6248d768dfa897ddc44e09a114ad5","_id":"z-schema@3.4.2","_shasum":"422dc3649938fc3e9f5d0d2279d122ce854dcdb4","_from":".","_npmVersion":"2.3.0","_nodeVersion":"1.0.4","_npmUser":{"name":"zaggino","email":"zaggino@gmail.com"},"maintainers":[{"name":"zaggino","email":"zaggino@gmail.com"}],"dist":{"shasum":"422dc3649938fc3e9f5d0d2279d122ce854dcdb4","tarball":"http://registry-npm.ywwl.com/z-schema/download/z-schema-3.4.2.tgz","integrity":"sha512-EZAUWEzmxJ6iKQA4MuHgRdDmUe9EChg0lHfTLufvTpxolwDthL9CY4tKp/r1JdG/hn+0WS0TASl+sfGcGmyP2A==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFacTLVXmNA04g4Aoipujljfmz2VYixJaCnUiFXD6ErcAiEAuA+BqSP/cqqgGrMRanQFFC7ZAP3sbSt8EsNqXkt5mfo="}],"size":423690,"noattachment":false,"key":"/z-schema/-/z-schema-3.4.2.tgz"},"directories":{},"readme":"# z-schema validator\n\n[![npm version](https://badge.fury.io/js/z-schema.svg)](http://badge.fury.io/js/z-schema)\n[![bower version](https://badge.fury.io/bo/z-schema.svg)](http://badge.fury.io/bo/z-schema)\n[![build status](https://travis-ci.org/zaggino/z-schema.svg?branch=master)](https://travis-ci.org/zaggino/z-schema)\n[![coverage status](https://coveralls.io/repos/zaggino/z-schema/badge.svg)](https://coveralls.io/r/zaggino/z-schema)\n\n[![Greenkeeper badge](https://badges.greenkeeper.io/zaggino/z-schema.svg)](https://greenkeeper.io/)\n[![dependencies Status](https://david-dm.org/zaggino/z-schema/status.svg)](https://david-dm.org/zaggino/z-schema)\n[![devDependencies Status](https://david-dm.org/zaggino/z-schema/dev-status.svg)](https://david-dm.org/zaggino/z-schema?type=dev)\n[![optionalDependencies Status](https://david-dm.org/zaggino/z-schema/optional-status.svg)](https://david-dm.org/zaggino/z-schema?type=optional)\n\n[![NPM](https://nodei.co/npm/z-schema.png?downloads=true&downloadRank=true)](https://nodei.co/npm/z-schema/)\n\n- version 3.0 runs also in the browsers now, run tests yourself [here](https://rawgit.com/zaggino/z-schema/master/test/SpecRunner.html)\n\n# Topics\n\n- [Usage](#usage)\n- [Features](#features)\n- [Options](#options)\n- [Benchmarks](#benchmarks)\n- [Contributors](#contributors)\n\n# Usage\n\nValidator will try to perform sync validation when possible for speed, but supports async callbacks when they are necessary.\n\n## Development:\n\nThese repository has several submodules and should be cloned as follows:\n>git clone **--recursive** https://github.com/zaggino/z-schema.git\n\n## CLI:\n\n```\nnpm install --global z-schema\nz-schema --help\nz-schema mySchema.json\nz-schema mySchema.json myJson.json\nz-schema --strictMode mySchema.json myJson.json\n```\n\n## NodeJS:\n\n```javascript\nvar ZSchema = require(\"z-schema\");\nvar options = ... // see below for possible option values\nvar validator = new ZSchema(options);\n```\n\n## Sync mode:\n\n```javascript\nvar valid = validator.validate(json, schema);\n// this will return a native error object with name and message\nvar error = validator.getLastError();\n// this will return an array of validation errors encountered\nvar errors = validator.getLastErrors();\n...\n```\n\n## Async mode:\n\n```javascript\nvalidator.validate(json, schema, function (err, valid) {\n    ...\n});\n```\n\n## Browser:\n\n```html\n<script type=\"text/javascript\" src=\"../dist/ZSchema-browser-min.js\"></script>\n<script type=\"text/javascript\">\n\tvar validator = new ZSchema();\n\tvar valid = validator.validate(\"string\", { \"type\": \"string\" });\n\tconsole.log(valid);\n</script>\n```\n\n## Remote references and schemas:\n\nIn case you have some remote references in your schemas, you have to download those schemas before using validator.\nOtherwise you'll get ```UNRESOLVABLE_REFERENCE``` error when trying to compile a schema.\n\n```javascript\nvar validator = new ZSchema();\nvar json = {};\nvar schema = { \"$ref\": \"http://json-schema.org/draft-04/schema#\" };\n\nvar valid = validator.validate(json, schema);\nvar errors = validator.getLastErrors();\n// valid === false\n// errors.length === 1\n// errors[0].code === \"UNRESOLVABLE_REFERENCE\"\n\nvar requiredUrl = \"http://json-schema.org/draft-04/schema\";\nrequest(requiredUrl, function (error, response, body) {\n\n    validator.setRemoteReference(requiredUrl, JSON.parse(body));\n\n    var valid = validator.validate(json, schema);\n    var errors = validator.getLastErrors();\n    // valid === true\n    // errors === undefined\n\n}\n```\n\nIf you're able to load schemas synchronously, you can use `ZSchema.setSchemaReader` feature:\n\n```javascript\nZSchema.setSchemaReader(function (uri) {\n    var someFilename = path.resolve(__dirname, \"..\", \"schemas\", uri + \".json\");\n    return JSON.parse(fs.readFileSync(someFilename, \"utf8\"));\n});\n```\n\n# Features\n\n- [Validate against subschema](#validate-against-subschema)\n- [Compile arrays of schemas and use references between them](#compile-arrays-of-schemas-and-use-references-between-them)\n- [Register a custom format](#register-a-custom-format)\n- [Automatic downloading of remote schemas](#automatic-downloading-of-remote-schemas)\n- [Prefill default values to object using format](#prefill-default-values-to-object-using-format)\n- [Define a custom timeout for all async operations](#asynctimeout)\n- [Disallow validation of empty arrays as arrays](#noemptyarrays)\n- [Disallow validation of empty strings as strings](#noemptystrings)\n- [Disallow schemas that don't have a type specified](#notypeless)\n- [Disallow schemas that contain unrecognized keywords and are not validated by parent schemas](#noextrakeywords)\n- [Assume additionalItems/additionalProperties are defined in schemas as false](#assumeadditional)\n- [Force additionalItems/additionalProperties to be defined in schemas](#forceadditional)\n- [Force items to be defined in array type schemas](#forceitems)\n- [Force minItems to be defined in array type schemas](#forceminitems)\n- [Force maxItems to be defined in array type schemas](#forcemaxitems)\n- [Force minLength to be defined in string type schemas](#forceminlength)\n- [Force maxLength to be defined in string type schemas](#forcemaxlength)\n- [Force properties or patternProperties to be defined in object type schemas](#forceproperties)\n- [Ignore remote references to schemas that are not cached or resolvable](#ignoreunresolvablereferences)\n- [Ignore case mismatch when validating enum values](#enumCaseInsensitiveComparison)\n- [Only allow strictly absolute URIs to be used in schemas](#stricturis)\n- [Turn on z-schema strict mode](#strictmode)\n- [Set validator to collect as many errors as possible](#breakonfirsterror)\n- [Report paths in errors as arrays so they can be processed easier](#reportpathasarray)\n\n## Validate against subschema\n\nIn case you don't want to split your schema into multiple schemas using reference for any reason, you can use option schemaPath when validating:\n\n```javascript\nvar valid = validator.validate(cars, schema, { schemaPath: \"definitions.car.definitions.cars\" });\n```\n\nSee more details in the [test](/test/spec/schemaPathSpec.js).\n\n## Compile arrays of schemas and use references between them\n\nYou can use validator to compile an array of schemas that have references between them and then validate against one of those schemas:\n\n```javascript\nvar schemas = [\n    {\n        id: \"personDetails\",\n        type: \"object\",\n        properties: {\n            firstName: { type: \"string\" },\n            lastName: { type: \"string\" }\n        },\n        required: [\"firstName\", \"lastName\"]\n    },\n    {\n        id: \"addressDetails\",\n        type: \"object\",\n        properties: {\n            street: { type: \"string\" },\n            city: { type: \"string\" }\n        },\n        required: [\"street\", \"city\"]\n    },\n    {\n        id: \"personWithAddress\",\n        allOf: [\n            { $ref: \"personDetails\" },\n            { $ref: \"addressDetails\" }\n        ]\n    }\n];\n\nvar data = {\n    firstName: \"Martin\",\n    lastName: \"Zagora\",\n    street: \"George St\",\n    city: \"Sydney\"\n};\n\nvar validator = new ZSchema();\n\n// compile & validate schemas first, z-schema will automatically handle array\nvar allSchemasValid = validator.validateSchema(schemas);\n// allSchemasValid === true\n\n// now validate our data against the last schema\nvar valid = validator.validate(data, schemas[2]);\n// valid === true\n```\n\n## Register a custom format\n\nYou can register any format of your own. Your sync validator function should always respond with a boolean:\n\n```javascript\nZSchema.registerFormat(\"xstring\", function (str) {\n    return str === \"xxx\";\n});\n```\n\nAsync format validators are also supported, they should accept two arguments, value and a callback to which they need to respond:\n\n```javascript\nZSchema.registerFormat(\"xstring\", function (str, callback) {\n    setTimeout(function () {\n        callback(str === \"xxx\");\n    }, 1);\n});\n```\n## Helper method to check the formats that have been registered\n```javascript\nvar registeredFormats = ZSchema.getRegisteredFormats();\n//registeredFormats will now contain an array of all formats that have been registered with z-schema\n```\n## Automatic downloading of remote schemas\n\nAutomatic downloading of remote schemas was removed from version ```3.x``` but is still possible with a bit of extra code,\nsee [this test](test/spec/AutomaticSchemaLoadingSpec.js) for more information on this.\n\n## Prefill default values to object using format\n\nUsing format, you can pre-fill values of your choosing into the objects like this:\n\n```javascript\nZSchema.registerFormat(\"fillHello\", function (obj) {\n    obj.hello = \"world\";\n    return true;\n});\n\nvar data = {};\n\nvar schema = {\n    \"type\": \"object\",\n    \"format\": \"fillHello\"\n};\n\nvalidator.validate(data, schema);\n// data.hello === \"world\"\n```\n\n# Options\n\n## asyncTimeout\n\nDefines a time limit, which should be used when waiting for async tasks like async format validators to perform their validation,\nbefore the validation fails with an ```ASYNC_TIMEOUT``` error.\n\n```javascript\nvar validator = new ZSchema({\n    asyncTimeout: 2000\n});\n```\n\n## noEmptyArrays\n\nWhen true, validator will assume that minimum count of items in any ```array``` is 1, except when ```minItems: 0``` is explicitly defined.\n\n```javascript\nvar validator = new ZSchema({\n    noEmptyArrays: true\n});\n```\n\n## noEmptyStrings\n\nWhen true, validator will assume that minimum length of any string to pass type ```string``` validation is 1, except when ```minLength: 0``` is explicitly defined.\n\n```javascript\nvar validator = new ZSchema({\n    noEmptyStrings: true\n});\n```\n\n## noTypeless\n\nWhen true, validator will fail validation for schemas that don't specify a ```type``` of object that they expect.\n\n```javascript\nvar validator = new ZSchema({\n    noTypeless: true\n});\n```\n\n## noExtraKeywords\n\nWhen true, validator will fail for schemas that use keywords not defined in JSON Schema specification and doesn't provide a parent schema in ```$schema``` property to validate the schema.\n\n```javascript\nvar validator = new ZSchema({\n    noExtraKeywords: true\n});\n```\n\n## assumeAdditional\n\nWhen true, validator assumes that additionalItems/additionalProperties are defined as false so you don't have to manually fix all your schemas.\n\n```javascript\nvar validator = new ZSchema({\n    assumeAdditional: true\n});\n```\n\nWhen an array, validator assumes that additionalItems/additionalProperties are defined as false, but allows some properties to pass.\n\n```javascript\nvar validator = new ZSchema({\n    assumeAdditional: [\"$ref\"]\n});\n```\n\n## forceAdditional\n\nWhen true, validator doesn't validate schemas where additionalItems/additionalProperties should be defined to either true or false.\n\n```javascript\nvar validator = new ZSchema({\n    forceAdditional: true\n});\n```\n\n## forceItems\n\nWhen true, validator doesn't validate schemas where ```items``` are not defined for ```array``` type schemas.\nThis is to avoid passing anything through an array definition.\n\n```javascript\nvar validator = new ZSchema({\n    forceItems: true\n});\n```\n\n## forceMinItems\n\nWhen true, validator doesn't validate schemas where ```minItems``` is not defined for ```array``` type schemas.\nThis is to avoid passing zero-length arrays which application doesn't expect to handle.\n\n```javascript\nvar validator = new ZSchema({\n    forceMinItems: true\n});\n```\n\n## forceMaxItems\n\nWhen true, validator doesn't validate schemas where ```maxItems``` is not defined for ```array``` type schemas.\nThis is to avoid passing arrays with unlimited count of elements which application doesn't expect to handle.\n\n```javascript\nvar validator = new ZSchema({\n    forceMaxItems: true\n});\n```\n\n## forceMinLength\n\nWhen true, validator doesn't validate schemas where ```minLength``` is not defined for ```string``` type schemas.\nThis is to avoid passing zero-length strings which application doesn't expect to handle.\n\n```javascript\nvar validator = new ZSchema({\n    forceMinLength: true\n});\n```\n\n\n## forceMaxLength\n\nWhen true, validator doesn't validate schemas where ```maxLength``` is not defined for ```string``` type schemas.\nThis is to avoid passing extremly large strings which application doesn't expect to handle.\n\n```javascript\nvar validator = new ZSchema({\n    forceMaxLength: true\n});\n```\n\n## forceProperties\n\nWhen true, validator doesn't validate schemas where ```properties``` or ```patternProperties``` is not defined for ```object``` type schemas.\nThis is to avoid having objects with unexpected properties in application.\n\n```javascript\nvar validator = new ZSchema({\n    forceProperties: true\n});\n```\n\n## ignoreUnresolvableReferences\n\nWhen true, validator doesn't end with error when a remote reference is unreachable. **This setting is not recommended in production outside of testing.**\n\n```javascript\nvar validator = new ZSchema({\n    ignoreUnresolvableReferences: true\n});\n```\n## enumCaseInsensitiveComparison\n\nWhen true, validator will return a ```ENUM_CASE_MISMATCH``` when the enum values mismatch only in case.\n\n```javascript\nvar validator = new ZSchema({\n    enumCaseInsensitiveComparison: true\n});\n```\n\n## strictUris\n\nWhen true, all strings of format ```uri``` must be an absolute URIs and not only URI references. See more details in [this issue](https://github.com/zaggino/z-schema/issues/18).\n\n```javascript\nvar validator = new ZSchema({\n    strictUris: true\n});\n```\n\n## strictMode\n\nStrict mode of z-schema is currently equal to the following:\n\n```javascript\nif (this.options.strictMode === true) {\n    this.options.forceAdditional  = true;\n    this.options.forceItems       = true;\n    this.options.forceMaxLength   = true;\n    this.options.forceProperties  = true;\n    this.options.noExtraKeywords  = true;\n    this.options.noTypeless       = true;\n    this.options.noEmptyStrings   = true;\n    this.options.noEmptyArrays    = true;\n}\n```\n\n```javascript\nvar validator = new ZSchema({\n    strictMode: true\n});\n```\n\n## breakOnFirstError\n\ndefault: `false`<br />\nWhen true, will stop validation after the first error is found:\n\n```javascript\nvar validator = new ZSchema({\n    breakOnFirstError: true\n});\n```\n\n## reportPathAsArray\n\nReport error paths as an array of path segments instead of a string:\n\n```javascript\nvar validator = new ZSchema({\n    reportPathAsArray: true\n});\n```\n\n## ignoreUnknownFormats\n\nBy default, z-schema reports all unknown formats, formats not defined by JSON Schema and not registered using\n`ZSchema.registerFormat`, as an error.  But the\n[JSON Schema specification](http://json-schema.org/latest/json-schema-validation.html#anchor106) says that validator\nimplementations *\"they SHOULD offer an option to disable validation\"* for `format`.  That being said, setting this\noption to `true` will disable treating unknown formats as errlrs\n\n```javascript\nvar validator = new ZSchema({\n    ignoreUnknownFormats: true\n});\n```\n\n## includeErrors\n\nBy default, z-schema reports all errors. If interested only in a subset of the errors, passing the option `includeErrors` to `validate` will perform validations only for those errors.\n\n```javascript\nvar validator = new ZSchema();\n// will only execute validation for \"INVALID_TYPE\" error.\nvalidator.validate(json, schema, {includeErrors: [\"INVALID_TYPE\"]});\n```\n\n## customValidator\n\n**Warning**: Use only if know what you are doing. Always consider using [custom format](#register-a-custom-format) before using this option.\n\nRegister function to be called as part of validation process on every subshema encounter during validation.\n\nLet's make a real-life example with this feature.\nImagine you have number of transactions:\n```json\n{\n    \"fromId\": 1034834329,\n    \"toId\": 1034834543,\n    \"amount\": 200\n}\n```\nSo you write the schema:\n```json\n{\n    \"type\": \"object\",\n    \"properties\": {\n        \"fromId\": {\n            \"type\": \"integer\"\n        },\n        \"toId\": {\n            \"type\": \"integer\"\n        },\n        \"amount\": {\n            \"type\": \"number\"\n        }\n    }\n}\n```\nBut how to check that `fromId` and `toId` are never equal.\nIn JSON Schema Draft4 there is no possibility to do this.\nActually, it's easy to just write validation code for such simple payloads.\nBut what if you have to do the same check for many objects in different places of JSON payload.\nOne solution is to add custom keyword `uniqueProperties` with array of property names as a value. So in our schema we would need to add:\n```json\n\"uniqueProperties\": [\n    \"fromId\",\n    \"toId\"\n]\n```\nTo teach `z-schema` about this new keyword we need to write handler for it:\n```javascript\nfunction customValidatorFn(report, schema, json) {\n    // check if our custom property is present\n    if (Array.isArray(schema.uniqueProperties)) {\n        var seenValues = [];\n        schema.uniqueProperties.forEach(function (prop) {\n            var value = json[prop];\n            if (typeof value !== 'undefined') {\n                if (seenValues.indexOf(value) !== -1) {\n                    // report error back to z-schema core\n                    report.addCustomError(\"NON_UNIQUE_PROPERTY_VALUE\",\n                        \"Property \\\"{0}\\\" has non-unique value: {1}\",\n                        [prop, value], null, schema.description);\n                }\n                seenValues.push(value)\n            }\n        });\n    }\n}\n\nvar validator = new ZSchema({\n    // register our custom validator inside z-schema\n    customValidator: customValidatorFn\n});\n```\nLet's test it:\n```javascript\nvar data = {\n    fromId: 1034834346,\n    toId: 1034834346,\n    amount: 50\n};\n\nvalidator.validate(data, schema);\nconsole.log(validator.getLastErrors())\n//[ { code: 'NON_UNIQUE_PROPERTY_VALUE',\n//    params: [ 'toId', 1034834346 ],\n//    message: 'Property \"toId\" has non-unique value: 1034834346',\n//    path: '#/',\n//    schemaId: undefined } ]\n```\n**Note:** before creating your own keywords you should consider all compatibility issues.\n\n# Benchmarks\n\nSo how does it compare to version 2.x and others?\n\n**NOTE: these tests are purely orientational, they don't consider extra features any of the validator may support and implement**\n\n[rawgithub.com/zaggino/z-schema/master/benchmark/results.html](https://rawgithub.com/zaggino/z-schema/master/benchmark/results.html)\n\n# Contributors\n\nThanks for contributing to:\n\n- [Jeremy Whitlock](https://github.com/whitlockjc)\n- [Oleksiy Krivoshey](https://github.com/oleksiyk)\n\nand to everyone submitting [issues](https://github.com/zaggino/z-schema/issues) on GitHub\n","publish_time":1422935377328,"_cnpm_publish_time":1422935377328,"dist-tags":{"beta":"7.0.0-beta.5","latest":"12.5.0"}}