Validation

JSON Schema

Convert v.* validation schemas to JSON Schema 2020-12 with toJSONSchema(), the dialect of OpenAPI 3.1, and read the schemas a validate() middleware carries.

5 min readUpdated DocumentationEdit this page
On this page5

Every v.* schema in @axiljs/validation converts to JSON Schema 2020-12, the dialect of OpenAPI 3.1. The schema you validate requests with is the same one you publish, so an OpenAPI document, a typed client or a form builder never has to describe the input a second time.

Note

New in 0.4.0.

TypeScript
TS
1import { toJSONSchema, v } from '@axiljs/validation'
2
3const createUser = v.object({
4  name:  v.string().min(2).max(100),
5  email: v.string().email(),
6  age:   v.number().integer().min(0).optional(),
7  role:  v.enum(['admin', 'user']).default('user'),
8  bio:   v.string().nullable()
9})
10
11createUser.toJSONSchema()
12// {
13//   type: 'object',
14//   properties: {
15//     name:  { type: 'string', minLength: 2, maxLength: 100 },
16//     email: { type: 'string', format: 'email' },
17//     age:   { type: 'integer', minimum: 0 },
18//     role:  { type: 'string', enum: ['admin', 'user'], default: 'user' },
19//     bio:   { type: ['string', 'null'] }
20//   },
21//   required: ['name', 'email', 'bio']
22// }

API

ExportDescription
schema.toJSONSchema()Method on every validator. Returns the JSON Schema of the input it accepts
toJSONSchema(schema, options?)Same as schema.toJSONSchema(); with { $schema: true } the root also gets $schema: JSON_SCHEMA_DIALECT
JSON_SCHEMA_DIALECT'https://json-schema.org/draft/2020-12/schema'
VALIDATION_SCHEMASSymbol.for('axiljs.validation.schemas'), the key under which validate() exposes its schemas
TypesJSONSchema, JSONSchemaType, ToJSONSchemaOptions, JSONSchemaConvertible
TypeScript
TS
1import { toJSONSchema, v } from '@axiljs/validation'
2
3toJSONSchema(v.string(), { $schema: true })
4// { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'string' }

toJSONSchema() accepts anything with a toJSONSchema() method (JSONSchemaConvertible). Each call returns a new object.

Mapping

BuilderJSON Schema
v.string()type: 'string'
.min(n) / .max(n) on stringsminLength / maxLength
.pattern(regex)pattern: the regex source; flags (i, m, u, …) are dropped
.email() / .url()format: 'email' / format: 'uri' (email wins when both are set)
v.number()type: 'number', or type: 'integer' with .integer()
.min(n) / .max(n) on numbersminimum / maximum
.positive()exclusiveMinimum: 0
v.boolean()type: 'boolean'
v.enum([...])type: 'string', enum
v.literal(x)const: x with its type (string, boolean, integer, number; null for v.literal(null))
v.array(item)type: 'array', items
.min(n) / .max(n) on arraysminItems / maxItems
v.object(shape)type: 'object', properties, required
v.record(value)type: 'object', additionalProperties: the value schema
v.union([...])anyOf
.optional()Left out of the parent object's required
.default(x)default: x, and left out of the parent's required
.nullable()type: [T, 'null']; an enum gains null; a const or anyOf gains { type: 'null' }
.custom(fn) / .transform(fn)Nothing: not representable
.trim()Nothing; minLength / maxLength are emitted unchanged

Examples of the less obvious cases:

TypeScript
TS
1v.enum(['a', 'b']).nullable().toJSONSchema()
2// { type: ['string', 'null'], enum: ['a', 'b', null] }
3
4v.literal('x').nullable().toJSONSchema()
5// { anyOf: [{ type: 'string', const: 'x' }, { type: 'null' }] }
6
7v.union([v.string(), v.number()]).toJSONSchema()
8// { anyOf: [{ type: 'string' }, { type: 'number' }] }
9
10v.record(v.number()).toJSONSchema()
11// { type: 'object', additionalProperties: { type: 'number' } }
12
13v.number().positive().toJSONSchema()
14// { type: 'number', exclusiveMinimum: 0 }

Input, not output

The JSON Schema describes the input a validator accepts, which is what a client must send:

  • .transform() changes the output of parse() and is not reflected. .custom() rules cannot be expressed and emit no constraint.
  • v.number() and v.boolean() also accept numeric and boolean strings ('5', 'true'), because query strings and form fields are always text (see coercion). The schema still says number / boolean: that is the type clients should send, and how a query parameter is documented in OpenAPI.
  • Objects accept keys they do not declare (kept by default, removed by .strip()), so additionalProperties is not set on v.object().
  • .trim() length limits apply to the trimmed value, which JSON Schema cannot express.

Discovering the schemas of validate()

The middleware returned by validate() carries the schemas it checks. Tools such as generateOpenAPI() in @axiljs/core use them to document a route without importing @axiljs/validation:

TypeScript
TS
1import { validate, VALIDATION_SCHEMAS } from '@axiljs/validation'
2
3const mw = validate({ body: createUser, query: listQuery })
4
5mw.schemas.body                  // createUser
6mw[VALIDATION_SCHEMAS]           // the same object as mw.schemas
7mw.schemas.body?.toJSONSchema()  // JSON Schema of the body
  • Only the locations passed to validate() (body, params, query) are present.
  • Both properties are read-only and non-enumerable, and the schemas object is frozen.
  • Validation behaviour is unchanged. The returned middleware is typed as ValidatedMiddleware.

OpenAPI explains how each location becomes path parameters, query parameters or a request body.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY