What is ajv-keywords?
The ajv-keywords package extends AJV (Another JSON Schema Validator) with additional keywords for JSON schema validation. It allows for more complex validation scenarios beyond what is available in the standard JSON Schema.
What are ajv-keywords's main functionalities?
dynamicDefaults
Allows setting dynamic defaults for properties, such as generating timestamps for createdAt fields.
{"properties": {"createdAt": {"type": "string", "format": "date-time", "default": "dynamic", "dynamicDefault": "datetime"}}}
transform
Enables transformation of data before validation. For example, trimming whitespace and converting text to lowercase.
{"properties": {"email": {"type": "string", "transform": ["trim", "toLowerCase"]}}}
range
Introduces exclusive range validation for numeric values, allowing for minimum and maximum values to be exclusive.
{"properties": {"age": {"type": "number", "exclusiveRange": true, "minimum": 18, "maximum": 60}}}
Other packages similar to ajv-keywords
jsonschema
A JSON Schema validator that supports draft-04/06/07. It's similar to ajv-keywords in providing JSON schema validation but does not offer the same level of keyword extension for custom validation scenarios.
tv4
Tiny Validator (tv4) is a lightweight JSON Schema validator that supports draft-04. While it provides basic validation capabilities, it lacks the extensibility and additional keywords provided by ajv-keywords.
ajv-keywords
Custom JSON-Schema keywords for ajv validator
Install
npm install ajv-keywords
Usage
var Ajv = require('ajv');
var defineKeywords = require('ajv-keywords');
var ajv = new Ajv;
defineKeywords(ajv, 'instanceof');
ajv.validate({ instanceof: 'RegExp' }, /.*/);
ajv.validate({ instanceof: 'RegExp' }, '.*');
or if using in browser (to avoid adding unused code):
var Ajv = require('ajv');
var ajv = new Ajv;
var instanceofDefinition = require('ajv-keywords/keywords/instanceof')
ajv.addKeyword('instanceof', instanceofDefinition);
Keywords
typeof
Based on JavaScript typeof
operation.
The value of the keyword should be a string: "undefined"
, "string"
, "number"
, "object"
, "function"
, "boolean"
or "symbol"
.
To pass validation the result of typeof
operation on the value should be equal to the string.
ajv.validate({ typeof: 'undefined' }, undefined); // true
ajv.validate({ typeof: 'undefined' }, null); // false
instanceof
Based on JavaScript typeof
operation.
The value of the keyword should be a string: "Object"
, "Array"
, "Function"
, "Number"
, "String"
, "Date"
, "RegExp"
or "Buffer"
.
To pass validation the result of data instanceof ...
operation on the value should be true:
ajv.validate({ instanceof: 'Array' }, []); // true
ajv.validate({ instanceof: 'Array' }, {}); // false
You can add your own constructor function to be recognised by this keyword:
function MyClass() {}
instanceofDefinition.CONSTRUCTORS.MyClass = MyClass;
ajv.validate({ instanceof: 'MyClass' }, new MyClass);
License
MIT