Zod
Officialv5.9.4@kubb/plugin-zod
kubb add plugin-zod
Coerce input with Zod
Set coercion to convert form data and query strings with z.coerce before Zod validates them, and see which format checks each key turns off.
Turn on coercion
Pass true to coerce strings, numbers, and dates, or an object to pick the primitives. See Coercion for primitives in the Zod docs.
import { pluginZod } from '@kubb/plugin-zod'
pluginZod({ coercion: { numbers: true } })limit: z.int().optional(),limit: z.coerce.number().int().optional(),| Value | Effect |
|---|---|
false (default) | No coercion, except format: int64 fields, which use z.coerce.bigint() because JSON holds a number. With the adapter's integerType: 'number', they print z.int(). |
true | Coerces strings, numbers, and dates with z.coerce.string(), z.coerce.number(), and z.coerce.date(). |
{ dates?, strings?, numbers? } | Coerces only the primitives you pick. |
Coerce strings
strings prints string fields as z.coerce.string().
- It replaces the
base64,base64url,jwt,ulid,iban,duration, andhostnamevalidators, so Zod no longer checks those formats. email,uri,uuid,ipv4, andipv6keep their validator and are not coerced.
Coerce numbers
numbers coerces number and integer fields, and enums with a numeric format such as int32.
- Integers typed as
numberprint asz.coerce.number().int(), orz.coerce.number().check(z.int())with Zod Mini. The coerced call drops theint32anduint32range checks. format: int64fields typed asbigint, the adapter default, keepz.coerce.bigint().- When a coerced enum is the discriminator of a
oneOf, the union prints asz.union, becausez.discriminatedUnioncannot read coerced values. - Other enums are not coerced.
Coerce dates
dates coerces only fields typed as Date, which needs dateType: 'date' on the adapter.
- Fields kept as ISO strings are never coerced.
format: timefields are never coerced, becausenew Date()cannot parse a bareHH:mm:ss. For a time-of-day type such asTemporal.PlainTime, see Encode custom types.
Coerced fields run on Zod's interpreter when you turn on
compile. See Compile Zod schemas.