Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The ajv npm package is a fast JSON Schema validator that allows you to validate JSON data against a JSON schema. It supports the latest JSON Schema draft-07 and has several extensions. It can be used for data validation, data sanitization, and to ensure that JSON documents comply with a predefined schema.
Validate data against a JSON Schema
This feature allows you to compile a JSON Schema and use it to validate JSON data. If the data does not conform to the schema, the errors can be logged or handled as needed.
{"const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
"type": "object",
"properties": {
"foo": {"type": "integer"},
"bar": {"type": "string"}
},
"required": ["foo"]
};
const validate = ajv.compile(schema);
const valid = validate({foo: 1, bar: 'abc'});
if (!valid) console.log(validate.errors);"}
Add custom keywords
Ajv allows you to define custom keywords for a JSON Schema, which can be used to create custom validation rules that are not defined in the JSON Schema specification.
{"const Ajv = require('ajv');
const ajv = new Ajv();
ajv.addKeyword('even', {
validate: function(schema, data) {
return data % 2 === 0;
}
});
const schema = {"even": true};
const validate = ajv.compile(schema);
const valid = validate(2); // true
const invalid = validate(3); // false"}
Asynchronous validation
Ajv supports asynchronous schema compilation, which is useful when your JSON Schema depends on other schemas that need to be fetched remotely.
{"const Ajv = require('ajv');
const ajv = new Ajv({loadSchema: loadExternalSchema});
// Assume loadExternalSchema is a function that loads a schema asynchronously
ajv.compileAsync(schema).then(function(validate) {
const valid = validate(data);
if (!valid) console.log(validate.errors);
}).catch(function(err) {
console.error('Failed to compile schema:', err);
});"}
Joi is a powerful schema description language and data validator for JavaScript. Unlike ajv, which focuses on JSON Schema, Joi allows you to create validation schemas using a fluent API. It is often used for validating data in REST APIs.
Tiny Validator (tv4) is a small and fast JSON Schema (v4) validator. It is less feature-rich compared to ajv and does not support the latest JSON Schema specifications, but it is suitable for simple validation tasks.
The jsonschema package is another validator for JSON Schema that supports draft-04/06/07. It is not as fast as ajv but provides a straightforward API for validating JSON data against schemas.
One of the fastest JSON Schema validators for node.js. It uses doT templates to generate super-fast validating functions.
ajv implements full JSON Schema draft 4 standard:
addSchema
or compiled to be available)ajv passes all the tests from JSON Schema Test Suite (apart from the one that requires that 1.0
is not an integer).
Benchmark of the test suite - json-schema-benchmark.
Same benchmark run on faster CPU with node 0.12.
Benchmark of individual test cases by z-schema.
npm install ajv
var Ajv = require('ajv');
var ajv = Ajv(); // options can be passed
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
or
// ...
var valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
// ...
or
// ...
ajv.addSchema(schema, 'mySchema');
var valid = ajv.validate('mySchema', data);
if (!valid) console.log(ajv.errors);
// ...
ajv compiles schemas to functions and caches them in all cases (using stringified schema as a key - using json-stable-stringify), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.
Create ajv instance.
All the instance methods below are bound to the instance, so they can be used without the instance.
Generate validating function and cache the compiled schema for future use.
Validating function returns boolean and has properties errors
with the errors from the last validation (null
if there were no errors) and schema
with the reference to the original schema.
Validate data using passed schema (it will be compiled and cached).
Instead of the schema you can use the key that was previously passed to addSchema
, the schema id if it was present in the schema or any previously resolved reference.
Validation errors will be available in the errors
property of ajv instance (null
if there were no errors).
Add and compile schema(s). It does the same as .compile
with two differences:
array of schemas can be passed (schemas should have ids), the second parameter will be ignored.
key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.
Once the schema added it and all the references inside it can be referenced in other schemas and used to validate data.
In the current version all the referenced schemas should be added before the schema that uses them is compiled, so the circular references are not supported.
Retrieve compiled schema previously added with addSchema
. Validating function has schema
property with the reference to the original schema.
Add custom format to validate strings. It can also be used to replace pre-defined formats for ajv instance.
Strins be converted to RegExp.
Function should return validation result as true
or false
.
Custom formats can be also added via formats
option.
false
not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.addFormat
method.uniqueItems
keyword (true by default).false
to use .length
of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters.npm install js-beautify
to use this option. true
or js-beautify options can be passed.git submodule update --init
npm test
Custom formats support.
Errors are set to null
if there are no errors (previously empty array).
FAQs
Another JSON Schema Validator
The npm package ajv receives a total of 106,498,709 weekly downloads. As such, ajv popularity was classified as popular.
We found that ajv demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.