Create Ajv instance:
See Options
Generate validating function and cache the compiled schema for future use.
Validating function returns a boolean value (or promise for async schemas that must have $async: true property - see Asynchronous validation). This function has properties errors and schema. Errors encountered during the last validation are assigned to errors property (it is assigned null if there was no errors). schema property contains the reference to the original schema.
The schema passed to this method will be validated against meta-schema unless validateSchema option is false. If schema is invalid, an error will be thrown. See options.
In typescript returned validation function can be a type guard if you pass type parameter:
See more advanced example in the test (opens new window).
Generate serializing function based on the JTD schema (caches the schema) - only in JTD instance of Ajv (see example below).
Serializers compiled from JTD schemas can be more than 10 times faster than using JSON.stringify, because they do not traverse all the data, only the properties that are defined in the schema.
Properties not defined in the schema will not be included in serialized JSON, unless the schema has additionalProperties: true flag. It can also be beneficial from the application security point of view, as it prevents leaking accidentally/temporarily added additional properties to the API responses.
If you use JTD with typescript, the type for the schema can be derived from the data type, and generated serializer would only accept correct data type in this case:
Compiled serializers do NOT validate data!
It is assumed that the data is valid according to the schema.
Generate parsing function based on the JTD schema (caches the schema) - only in JTD instance of Ajv (see example below).
Parsers compiled from JTD schemas have comparable performance to JSON.parse* in case JSON string is valid according to the schema (and they do not just parse JSON - they ensure that parsed JSON is valid according to the schema as they parse), but they can be many times faster in case the string is invalid - for example, if schema expects an object, and JSON string is array the parser would fail on the first character.
Parsing will fail if there are properties not defined in the schema, unless the schema has additionalProperties: true flag.
If you use JTD with typescript, the type for the schema can be derived from the data type, and generated parser will return correct data type (see definitions example in the serialize section):
* As long as empty schema {} is not used - there is a possibility to improve performance in this case. Also, the performance of parsing discriminator schemas depends on the position of discriminator tag in the schema - the best parsing performance will be achieved if the tag is the first property - this is how compiled JTD serializers generate JSON in case of discriminator schemas.
Asynchronous version of compile method that loads missing remote schemas using asynchronous function in options.loadSchema. This function returns a Promise that resolves to a validation function. An optional callback passed to compileAsync will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when:
The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded.
You can asynchronously compile meta-schema by passing true as the second parameter.
Similarly to compile, it can return type guard in typescript.
See example in Asynchronous schema loading.
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).
In typescript this method can act as a type guard (similarly to function returned by compile method - see example there).
Save errors property
Every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later.
If the schema is asynchronous (has $async keyword on the top level) this method returns a Promise. See Asynchronous validation.
Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole.
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 is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.
Although addSchema does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.
By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by validateSchema option.
Method chaining
Ajv returns its instance for chaining from all methods prefixed add* and remove*:
Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of addSchema because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional option).
There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option meta is set to false. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See validateSchema.
Validates schema. This method should be used to validate schemas rather than validate due to the inconsistency of uri format in JSON Schema standard.
By default this method is called automatically when the schema is added, so you rarely need to use it directly.
If schema doesn't have $schema property, it is validated against draft 6 meta-schema (option meta should not be false).
If schema has $schema property, then the schema with this id (that should be previously added) is used to validate passed schema.
Errors will be available at ajv.errors.
Retrieve compiled schema previously added with addSchema by the key passed to addSchema or by its full reference (id). The returned validating function has schema property with the reference to the original schema.
Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.
Schema can be removed using:
If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.
Add format to validate strings or numbers.
If object is passed it should have properties validate, compare and async:
Formats can be also added via formats option.
Add validation keyword to Ajv instance.
Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.
Keyword must start with an ASCII letter, _ or $, and may continue with ASCII letters, numbers, _, $, -, or :. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
Example Keywords:
Keyword definition is an object with the following properties:
If only the property keyword is provided in the definition object, you can also pass the keyword name as the argument.
compile, macro and code are mutually exclusive, only one should be used at a time. validate can be used separately or in addition to compile or macro to support $data reference.
Keyword is validated only for applicable data types
If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate type keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed.
See User defined keywords for more details.
Returns keyword definition, false if the keyword is unknown.
Removes added or pre-defined keyword so you can redefine them.
While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results.
Compiled schemas and removed keywords
The schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use removeSchema method and compile them again.
Returns the text with all errors in a String.
Options can have properties separator (string used to separate errors, ", " by default) and dataVar (the variable name that instancePath is prefixed with, "data" by default).
In case of validation failure, Ajv assigns the array of errors to errors property of validation function (or to errors property of Ajv instance when validate or validateSchema methods were called). In case of asynchronous validation, the returned promise is rejected with exception Ajv.ValidationError that has errors property.
Each reported error is an object with the following properties:
For JTD schemas instancePath and schemaPath depend on the nature of the failure - the errors are consistent with RFC8927 (opens new window).
Properties of params object in errors depend on the keyword that failed validation.
In typescript, the ErrorObject is a discriminated union that allows to determine the type of error parameters based on the value of keyword:
Also see an example in this test (opens new window)
User-defined keywords can define other keyword parameters.
You can use ajv-i18n (opens new window) package to generate errors in other languages.
A logger instance can be passed via logger option to Ajv constructor. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown.
This section is moved to Initialization options page