const ajv = new Ajv({keywords: require("ajv-keywords/dist/definitions")(opts)})
To add one or several keywords via options:
const ajv = new Ajv({
keywords: [
require("ajv-keywords/dist/definitions/typeof")(),
require("ajv-keywords/dist/definitions/instanceof")(),
// select exports an array of 3 definitions - see "select" in docs
...require("ajv-keywords/dist/definitions/select")(opts),
],
})
opts is an optional object with a property defaultMeta - URI of meta-schema to use for keywords that use subschemas (select and deepProperties). The default is "http://json-schema.org/schema".
Keywords
Types
typeof
Based on JavaScript typeof operation.
The value of the keyword should be a string ("undefined", "string", "number", "object", "function", "boolean" or "symbol") or an array of strings.
To pass validation the result of typeof operation on the value should be equal to the string (or one of the strings in the array).
You can add your own constructor function to be recognised by this keyword:
class MyClass {}
const instanceofDef = require("ajv-keywords/dist/definitions/instanceof")
instanceofDef.CONSTRUCTORS.MyClass = MyClass
ajv.validate({instanceof: "MyClass"}, new MyClass()) // true
Please note: currently instanceof is not supported in standalone validation code - it has to be implemented as code keyword to support it (PR is welcome).
Keywords for numbers
range and exclusiveRange
Syntax sugar for the combination of minimum and maximum keywords (or exclusiveMinimum and exclusiveMaximum), also fails schema compilation if there are no numbers in the range.
The value of these keywords must be an array consisting of two numbers, the second must be greater or equal than the first one.
If the validated value is not a number the validation passes, otherwise to pass validation the value should be greater (or equal) than the first number and smaller (or equal) than the second number in the array.
This keyword allows to use regular expressions with flags in schemas, and also without "u" flag when needed (the standard pattern keyword does not support flags and implies the presence of "u" flag).
This keyword applies only to strings. If the data is not a string, the validation succeeds.
The value of this keyword can be either a string (the result of regexp.toString()) or an object with the properties pattern and flags (the same strings that should be passed to RegExp constructor).
Please note: currently uniqueItemProperties is not supported in standalone validation code - it has to be implemented as code keyword to support it (PR is welcome).
Keywords for objects
allRequired
This keyword allows to require the presence of all properties used in properties keyword in the same schema object.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be boolean.
If the value of the keyword is false, the validation succeeds.
If the value of the keyword is true, the validation succeeds if the data contains all properties defined in properties keyword (in the same schema object).
If the properties keyword is not present in the same schema object, schema compilation will throw exception.
This keyword allows to require the presence of any (at least one) property from the list.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be an array of strings, each string being a property name. For data object to be valid at least one of the properties in this array should be present in the object.
This keyword allows to require the presence of only one property from the list.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be an array of strings, each string being a property name. For data object to be valid exactly one of the properties in this array should be present in the object.
This keyword allows to require the presence of properties that match some pattern(s).
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword should be an array of strings, each string being a regular expression. For data object to be valid each regular expression in this array should match at least one property name in the data object.
If the array contains multiple regular expressions, more than one expression can match the same property name.
This keyword allows to prohibit that any of the properties in the list is present in the object.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword should be an array of strings, each string being a property name. For data object to be valid none of the properties in this array should be present in the object.
Please note: {prohibited: ['foo', 'bar']} is equivalent to {not: {anyRequired: ['foo', 'bar']}} (i.e. it has the same validation result for any data).
deepProperties
This keyword allows to validate deep properties (identified by JSON pointers).
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value should be an object, where keys are JSON pointers to the data, starting from the current position in data, and the values are JSON schemas. For data object to be valid the value of each JSON pointer should be valid according to the corresponding schema.
This keyword allows to check that some deep properties (identified by JSON pointers) are available.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value should be an array of JSON pointers to the data, starting from the current position in data. For data object to be valid each JSON pointer should be some existing part of the data.
Please note: these keywords are deprecated. It is recommended to use OpenAPI discriminator keyword supported by Ajv v8 instead of select.
These keywords allow to choose the schema to validate the data based on the value of some property in the validated data.
These keywords must be present in the same schema object (selectDefault is optional).
The value of select keyword should be a $data reference that points to any primitive JSON type (string, number, boolean or null) in the data that is validated. You can also use a constant of primitive type as the value of this keyword (e.g., for debugging purposes).
The value of selectCases keyword must be an object where each property name is a possible string representation of the value of select keyword and each property value is a corresponding schema (from draft-06 it can be boolean) that must be used to validate the data.
The value of selectDefault keyword is a schema (also can be boolean) that must be used to validate the data in case selectCases has no key equal to the stringified value of select keyword.
The validation succeeds in one of the following cases:
the validation of data using selected schema succeeds,
none of the schemas is selected for validation,
the value of select is undefined (no property in the data that the data reference points to).
If select value (in data) is not a primitive type the validation fails.
This keyword correctly tracks evaluated properties and items to work with unevaluatedProperties and unevaluatedItems keywords - only properties and items from the subschema that was used (one of selectCases subschemas or selectDefault subschema) are marked as evaluated.
Please note: these keywords require Ajv $data option to support $data reference.
This keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc.
This keyword only works if useDefaults options is used and not inside anyOf keywords etc., in the same way as default keyword treated by Ajv.
The keyword should be added on the object level. Its value should be an object with each property corresponding to a property name, in the same way as in standard properties keyword. The value of each property can be:
an identifier of dynamic default function (a string)
an object with properties func (an identifier) and args (an object with parameters that will be passed to this function during schema compilation - see examples).
The properties used in dynamicDefaults should not be added to required keyword in the same schema (or validation will fail), because unlike default this keyword is processed after validation.
There are several predefined dynamic default functions:
"timestamp" - current timestamp in milliseconds
"datetime" - current date and time as string (ISO, valid according to date-time format)
"date" - current date as string (ISO, valid according to date format)
"time" - current time as string (ISO, valid according to time format)
"random" - pseudo-random number in [0, 1) interval
"randomint" - pseudo-random integer number. If string is used as a property value, the function will randomly return 0 or 1. If object { func: 'randomint', args: { max: N } } is used then the default will be an integer number in [0, N) interval.
"seq" - sequential integer number starting from 0. If string is used as a property value, the default sequence will be used. If object { func: 'seq', args: { name: 'foo'} } is used then the sequence with name "foo" will be used. Sequences are global, even if different ajv instances are used.
When using the useDefaults option value "empty", properties and items equal to null or "" (empty string) will be considered missing and assigned defaults. Use allOfcompound keyword to execute dynamicDefaults before validation.
Please note: dynamic default functions are differentiated by the number of parameters they have (function.length). Functions that do not expect default must have one non-optional argument so that function.length > 0.
To report a security vulnerability, please use the
Tidelift security contact.
Tidelift will coordinate the fix and disclosure.
Please do NOT report security vulnerabilities via GitHub issues.
Open-source software support
Ajv-keywords is a part of Tidelift subscription - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.
ajv-keywords
Custom JSON-Schema keywords for Ajv validator
Please note: This readme file is for ajv-keywords v5.0.0 that should be used with ajv v8.
ajv-keywords v3 should be used with ajv v6.
Contents
* - keywords that modify data + - keywords that are not supported in standalone validation code
Install
To install version 4 to use with Ajv v7:
Usage
To add all available keywords:
To add a single keyword:
To add multiple keywords:
To add a single keyword directly (to avoid adding unused code):
To add all keywords via Ajv options:
To add one or several keywords via options:
optsis an optional object with a propertydefaultMeta- URI of meta-schema to use for keywords that use subschemas (selectanddeepProperties). The default is"http://json-schema.org/schema".Keywords
Types
typeofBased on JavaScript
typeofoperation.The value of the keyword should be a string (
"undefined","string","number","object","function","boolean"or"symbol") or an array of strings.To pass validation the result of
typeofoperation on the value should be equal to the string (or one of the strings in the array).instanceofBased on JavaScript
instanceofoperation.The value of the keyword should be a string (
"Object","Array","Function","Number","String","Date","RegExp"or"Promise") or an array of strings.To pass validation the result of
data instanceof ...operation on the value should be true:You can add your own constructor function to be recognised by this keyword:
Please note: currently
instanceofis not supported in standalone validation code - it has to be implemented ascodekeyword to support it (PR is welcome).Keywords for numbers
rangeandexclusiveRangeSyntax sugar for the combination of minimum and maximum keywords (or exclusiveMinimum and exclusiveMaximum), also fails schema compilation if there are no numbers in the range.
The value of these keywords must be an array consisting of two numbers, the second must be greater or equal than the first one.
If the validated value is not a number the validation passes, otherwise to pass validation the value should be greater (or equal) than the first number and smaller (or equal) than the second number in the array.
Keywords for strings
regexpThis keyword allows to use regular expressions with flags in schemas, and also without
"u"flag when needed (the standardpatternkeyword does not support flags and implies the presence of"u"flag).This keyword applies only to strings. If the data is not a string, the validation succeeds.
The value of this keyword can be either a string (the result of
regexp.toString()) or an object with the propertiespatternandflags(the same strings that should be passed to RegExp constructor).transformThis keyword allows a string to be modified during validation.
This keyword applies only to strings. If the data is not a string, the
transformkeyword is ignored.A standalone string cannot be modified, i.e.
data = 'a'; ajv.validate(schema, data);, because strings are passed by valueSupported transformations:
trim: remove whitespace from start and endtrimStart/trimLeft: remove whitespace from starttrimEnd/trimRight: remove whitespace from endtoLowerCase: convert to lower casetoUpperCase: convert to upper casetoEnumCase: change string case to be equal to one ofenumvalues in the schemaTransformations are applied in the order they are listed.
Note:
toEnumCaserequires that all allowed values are unique when case insensitive.Example: multiple transformations
Example:
enumcaseKeywords for arrays
uniqueItemPropertiesThe keyword allows to check that some properties in array items are unique.
This keyword applies only to arrays. If the data is not an array, the validation succeeds.
The value of this keyword must be an array of strings - property names that should have unique values across all items.
This keyword is contributed by @blainesch.
Please note: currently
uniqueItemPropertiesis not supported in standalone validation code - it has to be implemented ascodekeyword to support it (PR is welcome).Keywords for objects
allRequiredThis keyword allows to require the presence of all properties used in
propertieskeyword in the same schema object.This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be boolean.
If the value of the keyword is
false, the validation succeeds.If the value of the keyword is
true, the validation succeeds if the data contains all properties defined inpropertieskeyword (in the same schema object).If the
propertieskeyword is not present in the same schema object, schema compilation will throw exception.anyRequiredThis keyword allows to require the presence of any (at least one) property from the list.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be an array of strings, each string being a property name. For data object to be valid at least one of the properties in this array should be present in the object.
oneRequiredThis keyword allows to require the presence of only one property from the list.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword must be an array of strings, each string being a property name. For data object to be valid exactly one of the properties in this array should be present in the object.
patternRequiredThis keyword allows to require the presence of properties that match some pattern(s).
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword should be an array of strings, each string being a regular expression. For data object to be valid each regular expression in this array should match at least one property name in the data object.
If the array contains multiple regular expressions, more than one expression can match the same property name.
prohibitedThis keyword allows to prohibit that any of the properties in the list is present in the object.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value of this keyword should be an array of strings, each string being a property name. For data object to be valid none of the properties in this array should be present in the object.
Please note:
{prohibited: ['foo', 'bar']}is equivalent to{not: {anyRequired: ['foo', 'bar']}}(i.e. it has the same validation result for any data).deepPropertiesThis keyword allows to validate deep properties (identified by JSON pointers).
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value should be an object, where keys are JSON pointers to the data, starting from the current position in data, and the values are JSON schemas. For data object to be valid the value of each JSON pointer should be valid according to the corresponding schema.
deepRequiredThis keyword allows to check that some deep properties (identified by JSON pointers) are available.
This keyword applies only to objects. If the data is not an object, the validation succeeds.
The value should be an array of JSON pointers to the data, starting from the current position in data. For data object to be valid each JSON pointer should be some existing part of the data.
See json-schema-org/json-schema-spec#203 for an example of the equivalent schema without
deepRequiredkeyword.Keywords for all types
select/selectCases/selectDefaultPlease note: these keywords are deprecated. It is recommended to use OpenAPI discriminator keyword supported by Ajv v8 instead of
select.These keywords allow to choose the schema to validate the data based on the value of some property in the validated data.
These keywords must be present in the same schema object (
selectDefaultis optional).The value of
selectkeyword should be a $data reference that points to any primitive JSON type (string, number, boolean or null) in the data that is validated. You can also use a constant of primitive type as the value of this keyword (e.g., for debugging purposes).The value of
selectCaseskeyword must be an object where each property name is a possible string representation of the value ofselectkeyword and each property value is a corresponding schema (from draft-06 it can be boolean) that must be used to validate the data.The value of
selectDefaultkeyword is a schema (also can be boolean) that must be used to validate the data in caseselectCaseshas no key equal to the stringified value ofselectkeyword.The validation succeeds in one of the following cases:
If
selectvalue (in data) is not a primitive type the validation fails.This keyword correctly tracks evaluated properties and items to work with
unevaluatedPropertiesandunevaluatedItemskeywords - only properties and items from the subschema that was used (one ofselectCasessubschemas orselectDefaultsubschema) are marked as evaluated.Please note: these keywords require Ajv
$dataoption to support $data reference.dynamicDefaultsThis keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc.
This keyword only works if
useDefaultsoptions is used and not insideanyOfkeywords etc., in the same way as default keyword treated by Ajv.The keyword should be added on the object level. Its value should be an object with each property corresponding to a property name, in the same way as in standard
propertieskeyword. The value of each property can be:func(an identifier) andargs(an object with parameters that will be passed to this function during schema compilation - see examples).The properties used in
dynamicDefaultsshould not be added torequiredkeyword in the same schema (or validation will fail), because unlikedefaultthis keyword is processed after validation.There are several predefined dynamic default functions:
"timestamp"- current timestamp in milliseconds"datetime"- current date and time as string (ISO, valid according todate-timeformat)"date"- current date as string (ISO, valid according todateformat)"time"- current time as string (ISO, valid according totimeformat)"random"- pseudo-random number in [0, 1) interval"randomint"- pseudo-random integer number. If string is used as a property value, the function will randomly return 0 or 1. If object{ func: 'randomint', args: { max: N } }is used then the default will be an integer number in [0, N) interval."seq"- sequential integer number starting from 0. If string is used as a property value, the default sequence will be used. If object{ func: 'seq', args: { name: 'foo'} }is used then the sequence with name"foo"will be used. Sequences are global, even if different ajv instances are used.When using the
useDefaultsoption value"empty", properties and items equal tonullor""(empty string) will be considered missing and assigned defaults. UseallOfcompound keyword to executedynamicDefaultsbefore validation.You can add your own dynamic default function to be recognised by this keyword:
You also can define dynamic default that accept parameters, e.g. version of uuid:
Please note: dynamic default functions are differentiated by the number of parameters they have (
function.length). Functions that do not expect default must have one non-optional argument so thatfunction.length> 0.dynamicDefaultsis not supported in standalone validation code.Security contact
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
Please do NOT report security vulnerabilities via GitHub issues.
Open-source software support
Ajv-keywords is a part of Tidelift subscription - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.
License
MIT