What is ajv-formats?
The ajv-formats package provides support for string formats in JSON Schema validation using the AJV validator. It includes various string formats for date-time, email, hostname, ipv4, ipv6, uri, uri-reference, uuid, and more, which can be used to validate data against specific format requirements.
What are ajv-formats's main functionalities?
Date-time format validation
Validates that a string is a valid date-time representation according to the format specified in the JSON Schema.
{"type":"string","format":"date-time"}
Email format validation
Validates that a string is a valid email address.
{"type":"string","format":"email"}
URI format validation
Validates that a string is a valid URI.
{"type":"string","format":"uri"}
UUID format validation
Validates that a string is a valid UUID.
{"type":"string","format":"uuid"}
Other packages similar to ajv-formats
jsonschema
The jsonschema package is a JSON Schema validator that also provides format validation. It supports similar functionalities to ajv-formats but is implemented in a different way and may have different performance characteristics.
tv4
tv4 is a tiny validator for JSON Schema v4. Like ajv-formats, it can validate formats specified in a JSON Schema, but it is less feature-rich and not as actively maintained as AJV.
joi
Joi is a powerful schema description language and data validator for JavaScript. Unlike ajv-formats, Joi does not use JSON Schema but instead provides its own schema definition language, which can be more expressive and easier to use for some developers.
ajv-formats
Plugin for AJV that adds support for some of draft2019 formats.
Currently, the iri
, idn-email
, and duration
formats are supported.
Installation
npm install ajv-formats
Usage
The main export is an apply
function that patches an existing instance of ajv
.
const Ajv = require('ajv');
const apply = require('ajv-formats');
const ajv = new Ajv();
apply(ajv);
let schema = {
type: 'string',
format: 'idn-email'
};
ajv.validate(schema, 'квіточка@пошта.укр') // returns true
Alternately, the formats can be passed as an option when creating a new ajv
instance.
const Ajv = require('ajv');
const formats = require('ajv-draft2019-formats/formats');
const ajv = new Ajv({formats});
let schema = {
type: 'string',
format: 'idn-email'
};
ajv.validate(schema, 'квіточка@пошта.укр') // returns true
Formats
iri
Scheme are checked against the list of IANA schemes for a valid scheme and path only.
For 'mailto' schemes, all of the to:
addresses are validated.
idn-email
isemail
is used to check the validity of the email.
duration
The string is checked against a regex.