docs/guide/formats.md
From version 7 Ajv does not include formats defined by JSON Schema specification - these and several other formats are provided by ajv-formats plugin.
To add all formats from this plugin:
<code-group> <code-block title="JavaScript"> ```javascript const Ajv = require("ajv") const addFormats = require("ajv-formats")const ajv = new Ajv() addFormats(ajv)
</code-block>
<code-block title="TypeScript">
```typescript
import Ajv from "ajv"
import addFormats from "ajv-formats"
const ajv = new Ajv()
addFormats(ajv)
See ajv-formats documentation for further details.
It is recommended NOT to use "format" keyword implementations with untrusted data, as they may use potentially unsafe regular expressions (even though known issues are fixed) - see ReDoS attack.
::: danger Format validation of untrusted data If you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. :::
The following formats are defined in ajv-formats for string validation with "format" keyword:
::: warning Additional formats in ajv-formats-draft2019
JSON Schema draft-07 also defines formats iri, iri-reference, idn-hostname and idn-email for URLs, hostnames and emails with international characters. These formats are available in ajv-formats-draft2019 plugin.
:::
You can add and replace any formats using addFormat method:
ajv.addFormat("identifier", /^a-z\$_[a-zA-Z$_0-9]*$/)
Ajv also allows defining the formats that would be applied to numbers only:
ajv.addFormat("byte", {
type: "number",
validate: (x) => x >= 0 && x <= 255 && x % 1 == 0,
})
If you use formats from ajv-formats package, standalone validation code will be supported out of the box.
::: warning Standalone code and Ajv versions
You need to make sure that ajv-formats imports the same version and the same code of ajv as the one you use in your application for standalone validation code to work (because of instanceof check that is currently used).
npm and other package managers may not update the version of ajv dependency of ajv-formats when you update version of ajv in your application - the workaround is to use clean npm installation.
:::
If you define your own formats, for standalone code generation to work you need to pass the code snippet that evaluates to an object with all defined formats to the option code.formats: