Jsonschema
JSON Schema validation
Install / Use
/learn @tdegrunt/JsonschemaREADME
jsonschema
JSON schema validator, which is designed to be fast and simple to use. JSON Schema versions through draft-07 are fully supported.
Contributing & bugs
Please fork the repository, make the changes in your fork and include tests. Once you're done making changes, send in a pull request.
Bug reports
Please include a test which shows why the code fails.
Installation
You can install jsonschema using a package manager like npm, yarn, or bun:
npm install jsonschema
Usage
Simple
Simple object validation using JSON schemas.
var Validator = require('jsonschema').Validator;
var v = new Validator();
var instance = 4;
var schema = {"type": "number"};
console.log(v.validate(instance, schema));
Even simpler
var validate = require('jsonschema').validate;
console.log(validate(4, {"type": "number"}));
Complex example, with split schemas and references
var Validator = require('jsonschema').Validator;
var v = new Validator();
// Address, to be embedded on Person
var addressSchema = {
"id": "/SimpleAddress",
"type": "object",
"properties": {
"lines": {
"type": "array",
"items": {"type": "string"}
},
"zip": {"type": "string"},
"city": {"type": "string"},
"country": {"type": "string"}
},
"required": ["country"]
};
// Person
var schema = {
"id": "/SimplePerson",
"type": "object",
"properties": {
"name": {"type": "string"},
"address": {"$ref": "/SimpleAddress"},
"votes": {"type": "integer", "minimum": 1}
}
};
var p = {
"name": "Barack Obama",
"address": {
"lines": [ "1600 Pennsylvania Avenue Northwest" ],
"zip": "DC 20500",
"city": "Washington",
"country": "USA"
},
"votes": "lots"
};
v.addSchema(addressSchema, '/SimpleAddress');
console.log(v.validate(p, schema));
Returned ValidatorResult object, will show this example is NOT valid since: "votes": "lots" is not an integer.
Example for Array schema
var arraySchema = {
"type": "array",
"items": {
"properties": {
"name": { "type": "string" },
"lastname": { "type": "string" }
},
"required": ["name", "lastname"]
}
};
For a comprehensive, annotated example illustrating all possible validation options, see examples/all.js
Features
Definitions
All schema definitions are supported, $schema is ignored.
Types
All types are supported
Handling undefined
undefined is not a value known to JSON, and by default, the validator treats it as if it is not invalid. i.e., it will return valid.
var res = validate(undefined, {type: 'string'});
res.valid // true
This behavior may be changed with the "required" option:
var res = validate(undefined, {type: 'string'}, {required: true});
res.valid // false
Formats
Disabling the format keyword.
You may disable format validation by providing disableFormat: true to the validator
options.
String Formats
All formats are supported, phone numbers are expected to follow the E.123 standard.
Custom Formats
You may add your own custom format functions. Format functions accept the input
being validated and return a boolean value. If the returned value is true, then
validation succeeds. If the returned value is false, then validation fails.
- Formats added to
Validator.prototype.customFormatsdo not affect previously instantiated Validators. This is to prevent validator instances from being altered once created. It is conceivable that multiple validators may be created to handle multiple schemas with different formats in a program. - Formats added to
validator.customFormatsaffect only that Validator instance.
Here is an example that uses custom formats:
Validator.prototype.customFormats.myFormat = function(input) {
return input === 'myFormat';
};
var validator = new Validator();
validator.validate('myFormat', {type: 'string', format: 'myFormat'}).valid; // true
validator.validate('foo', {type: 'string', format: 'myFormat'}).valid; // false
Results
By default, results will be returned in a ValidatorResult object with the following properties:
instance: any.schema: Schema.errors: ValidationError[].valid: boolean.
Each item in errors is a ValidationError with the following properties:
- path: array. An array of property keys or array offsets, indicating where inside objects or arrays the instance was found.
- property: string. Describes the property path. Starts with
instance, and is delimited with a dot (.). - message: string. A human-readable message for debugging use. Provided in English and subject to change.
- schema: object. The schema containing the keyword that failed
- instance: any. The instance that failed
- name: string. The keyword within the schema that failed.
- argument: any. Provides information about the keyword that failed.
The validator can be configured to throw in the event of a validation error:
-
If the
throwFirstoption is set, the validator will terminate validation at the first encountered error and throw aValidatorResultErrorobject. -
If the
throwAlloption is set, the validator will throw aValidatorResultErrorobject after the entire instance has been validated. -
If the
throwErroroption is set, it will throw at the first encountered validation error (likethrowFirst), but theValidationErrorobject itself will be thrown. Note that, despite the name, this does not inherit from Error likeValidatorResultErrordoes.
The ValidatorResultError object has the same properties as ValidatorResult and additionally inherits from Error.
"nestedErrors" option
When oneOf or anyOf validations fail, errors that caused any of the sub-schemas referenced therein to fail are normally suppressed, because it is not necessary to fix all of them. And in the case of oneOf, it would itself be an error to fix all of the listed errors.
This behavior may be configured with options.nestedErrors. If truthy, it will emit all the errors from the subschemas. This option may be useful when troubleshooting validation errors in complex schemas:
var schema = {
oneOf: [
{ type: 'string', minLength: 32, maxLength: 32 },
{ type: 'string', maxLength: 16 },
{ type: 'number' },
]
};
var validator = new Validator();
var result = validator.validate('This string is 28 chars long', schema, {nestedErrors: true});
// result.toString() reads out:
// 0: instance does not meet minimum length of 32
// 1: instance does not meet maximum length of 16
// 2: instance is not of a type(s) number
// 3: instance is not exactly one from [subschema 0],[subschema 1],[subschema 2]
Localizing Error Messages
To provide localized, human-readable errors, use the name string as a translation key. Feel free to open an issue for support relating to localizing error messages. For example:
var localized = result.errors.map(function(err){
return localeService.translate(err.name);
});
Custom keywords
Specify your own JSON Schema keywords with the validator.attributes property:
validator.attributes.contains = function validateContains(instance, schema, options, ctx) {
if(typeof instance !== 'string') return;
if(typeof schema.contains !== 'string') throw new jsonschema.SchemaError('"contains" expects a string', schema);
if(instance.indexOf(schema.contains)<0){
return 'does not contain the string ' + JSON.stringify(schema.contains);
}
}
var result = validator.validate("I am an instance", { type:"string", contains: "I am" });
// result.valid === true;
The instance passes validation if the function returns nothing. A single validation error is produced
if the function returns a string. Any number of errors (maybe none at all) may be returned by passing a
ValidatorResult object, which may be used like so:
var result = new ValidatorResult(instance, schema, options, ctx);
while(someErrorCondition()){
result.addError('fails some validation test');
}
return result;
Dereferencing schemas
Sometimes you may want to download schemas from remote sources, like a database, or over HTTP. When importing a schema,
unknown references are inserted into the validator.unresolvedRefs Array. Asynchronously shift elements off this array and import
them:
var Validator = require('jsonschema').Validator;
var v = new Validator();
v.addSchema(initialSchema);
function importNextSchema(){
var nextSchema = v.unresolvedRefs.shift();
if(!nextSchema){ done(); return; }
databaseGet(nextSchema, function(schema){
v.addSchema(schema);
importNextSchema();
});
}
importNextSchema();
Disallowing unknown attributes
Sometimes you may want to disallow unknown attributes passed in the body of the request, in order to disallow those unknown attributes before the validation of the body, you need to set additionalProperties to false.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Accounting Resource - Add Item",
"type": "object",
"additionalProperties": false,
"properties": {
"itemNumber": {
"type":"string"
},
"title": {
"type":"string"
},
"description": {
"type":"string"
}
},
"required": [
"itemNumber",
"title",
"description"
]
}
Default base URI
Schemas should typically have an id with an absolute, full URI. However if the schema you are using contains only relative URI references, the base option will be used to resolve these.
This following example would throw a SchemaError if the base option were unset:
var result = validate(["Name"], {
id: "/schema.json",
type: "array",
items: { $ref: "
