Schema Builder
Fluent, Zod-like schema builder for request validation with numeric and boolean string coercion and exported validator classes.
Usage
1import { v } from '@axiljs/validation'
2
3const schema = v.object({
4 name: v.string().min(2).max(100).trim(),
5 email: v.string().email(),
6 age: v.number().integer().min(0).max(150).optional(),
7 role: v.enum(['admin', 'user']),
8 tags: v.array(v.string()).max(10).optional()
9})
10
11const result = schema.parse(data)
12if (!result.success) console.log(result.errors) // [{ path, message, code }]
13else console.log(result.data)Builders
| Builder | Methods |
|---|---|
v.string() | .min(n), .max(n), .pattern(regex), .email(), .url(), .trim() |
v.number() | .min(n), .max(n), .integer(), .positive() |
v.boolean() | — |
v.array(item) | .min(n), .max(n) |
v.object(shape) | .strip() removes fields not in the shape |
v.enum(values) | — |
v.literal(value) | — |
v.union([a, b]) | — |
v.record(valueSchema) | — |
Modifiers
Every validator supports .optional(), .nullable(), .default(value), .custom(fn, message?) and .transform(fn). Transforms run after validation and change what parse() and validate() return.
Coercion of string input
Query strings, route params and form bodies arrive as strings, so numbers and booleans accept their string forms and parse() returns the converted value.
| Validator | Accepts | Returns |
|---|---|---|
v.number() | 5, '5', ' 2.5 ' | 5, 5, 2.5 |
v.boolean() | true, 'true', '1' / false, 'false', '0' | true / false |
v.object({ page: v.number().integer().min(1) }).parse({ page: '2' })
// { success: true, data: { page: 2 } }Note
Changed in 0.3.3: v.number() now returns numeric strings as numbers (earlier versions accepted '5' but passed the string through unchanged), and v.boolean() coerces 'true'/'false'/'1'/'0'. Blank or whitespace-only strings are now rejected by v.number() (previously '' passed as 0), as are NaN, Infinity and non-numeric strings. Rules such as .min() and .custom() see the coerced value.
Exported validator classes
BaseValidator, StringValidator, NumberValidator, BooleanValidator, ArrayValidator, ObjectValidator, EnumValidator, LiteralValidator, UnionValidator and RecordValidator are exported from @axiljs/validation, along with the ValidationResult, ValidationError, SchemaShape, InferShape, InferValidator and Primitive types.
Tip
Fixed in 0.3.3: exporting a schema (export const userSchema = v.object(...)) from a project compiled with declaration: true no longer fails with TS4094, because the inferred types now refer to exported classes.
1import { v, type InferValidator } from '@axiljs/validation'
2
3export const userSchema = v.object({
4 name: v.string().min(1),
5 admin: v.boolean().default(false)
6})
7
8export type User = InferValidator<typeof userSchema>Was this page helpful?