JSON schema validator
npm install z-schema

- What
- Versions
- Usage
- Features
- Options
- Contributing
- Contributors
What is a JSON Schema? Find here: https://json-schema.org/
- v6 - old version which has been around a long time, supports JSON Schema draft-04
- v7 - modernized version (to ESM module with Typescript) which passes all tests from JSON Schema Test Suite for draft-04
- v8 - by default assumes all schemas without $schema tag are draft-04, the old behaviour from v7 can be explicitly turned on by specifying validator = new ZSchema({ version: 'none' });
Validator will try to perform sync validation when possible for speed, but supports async callbacks when they are necessary.
``javascript`
import ZSchema from 'z-schema';
const validator = new ZSchema();
console.log(validator.validate(1, { type: 'number' })); // true
console.log(validator.validate(1, { type: 'string' })); // false
`javascript`
const ZSchema = require('z-schema');
const validator = new ZSchema();
console.log(validator.validate(1, { type: 'number' })); // true
console.log(validator.validate(1, { type: 'string' })); // false
`bash`
npm install --global z-schema
z-schema --help
z-schema mySchema.json
z-schema mySchema.json myJson.json
z-schema --strictMode mySchema.json myJson.json
`javascript`
var valid = validator.validate(json, schema);
// this will return a native error object with name and message
var error = validator.getLastError();
// this will return an array of validation errors encountered
var errors = validator.getLastErrors();
...
ZSchema supports custom format validators that can perform both synchronous and asynchronous validation. This example shows how to validate a person payload with:
- Async validation: User ID against a database
- Async validation: Postcode against an external service
- Sync validation: Phone number format
`typescript
import ZSchema from 'z-schema';
import db from './db';
// Initialize ZSchema
const validator = new ZSchema();
// Register async and sync format validators
validator.registerFormat('user-exists', async (input: unknown): Promise
if (typeof input !== 'number') return false;
const user = await db.getUserById(input);
return user != null;
});
validator.registerFormat('valid-postcode', async (input: unknown): Promise
if (typeof input !== 'string') return false;
const postcode = await db.getPostcode(input);
return postcode != null;
});
validator.registerFormat('phone-number', (input: unknown): boolean => {
if (typeof input !== 'string') return false;
const phoneRegex = /^\+?[1-9]\d{1,14}$/;
return phoneRegex.test(input);
});
// Define the JSON Schema
const personSchema = {
$schema: 'http://json-schema.org/draft-04/schema#',
type: 'object',
required: ['personId', 'address'],
properties: {
personId: {
type: 'number',
format: 'user-exists',
},
address: {
type: 'object',
required: ['postcode', 'phone'],
properties: {
postcode: {
type: 'string',
format: 'valid-postcode',
},
phone: {
type: 'string',
format: 'phone-number',
},
},
},
},
};
// Example payload
const payload = {
personId: 'user123',
address: {
postcode: 'SW1A 1AA',
phone: '+441234567890',
},
};
// Validate asynchronously
try {
await validator.validateAsync(payload, personSchema);
console.log('✅ Validation successful!');
} catch (err) {
console.log('❌ Validation failed:', err);
}
// or validate without try-catch
const res = await validator.validateAsyncSafe(payload, personSchema);
if (res.valid) {
console.log('✅ Validation successful!');
} else {
console.log('❌ Validation failed:', res.errs);
}
`
`html`
In case you have some remote references in your schemas, you have to download those schemas before using validator.
Otherwise you'll get UNRESOLVABLE_REFERENCE error when trying to compile a schema.
`javascript
var validator = new ZSchema();
var json = {};
var schema = { "$ref": "http://json-schema.org/draft-04/schema#" };
var valid = validator.validate(json, schema);
var errors = validator.getLastErrors();
// valid === false
// errors.length === 1
// errors[0].code === "UNRESOLVABLE_REFERENCE"
var requiredUrl = "http://json-schema.org/draft-04/schema";
request(requiredUrl, function (error, response, body) {
validator.setRemoteReference(requiredUrl, JSON.parse(body));
var valid = validator.validate(json, schema);
var errors = validator.getLastErrors();
// valid === true
// errors === undefined
}
`
If you're able to load schemas synchronously, you can use ZSchema.setSchemaReader feature:
`javascript``
ZSchema.setSchemaReader(function (uri) {
var someFilename = path.resolve(__dirname, '..', 'schemas', uri + '.json');
return JSON.parse(fs.readFileSync(someFilename, 'utf8'));
});
See FEATURES.md for a full list of features.
See OPTIONS.md for all available options and their descriptions.
These repository has several submodules and should be cloned as follows:
> git clone --recursive https://github.com/zaggino/z-schema.git
Big thanks to:
and to everyone submitting issues on GitHub