Elysia Tools
Navigation
Validation Libraries
Zod 4.1.8 offline validation examples
Strict object boundaries; Defaults are not coercion; Cross-field order.
Samples
Entries inside this sample collection
Strict object boundaries
Run card1.cjs: positive integer id, nonempty label, no extra keys.
Tags
offline, synthetic, verified-input
// Node.js CommonJS, tested with zod 4.1.8. No I/O beyond console.
const { z } = require('zod');
const Item = z.strictObject({ id: z.number().int().positive(), label: z.string().min(1) });
const cases = [{id:1,label:'Demo'}, {id:0,label:'Demo'}, {id:1,label:''}, {id:1,label:'Demo',extra:true}];
const results = cases.map(x => Item.safeParse(x).success);
if (JSON.stringify(results) !== '[true,false,false,false]') throw Error('Unexpected validation');
console.log(results);
Defaults are not coercion
Run card2.cjs with undefined, string 25 and null.
Tags
offline, synthetic, verified-input
const { z } = require('zod');
// Default handles undefined, not null. No implicit string-number coercion.
const Limit = z.number().int().min(1).max(100).default(10);
const missing = Limit.parse(undefined);
const text = Limit.safeParse('25').success;
const nullValue = Limit.safeParse(null).success;
if (missing !== 10 || text || nullValue) throw Error('Unexpected default behavior');
console.log({missing, text, nullValue});
Cross-field order
Run card3.cjs for spans 2→5, 2→2 and 5→2.
Tags
offline, synthetic, verified-input
const { z } = require('zod');
const Span = z.object({start:z.number(),end:z.number()}).refine(x => x.end >= x.start, {message:'end must not precede start',path:['end']});
const good = Span.safeParse({start:2,end:5});
const equal = Span.safeParse({start:2,end:2});
const bad = Span.safeParse({start:5,end:2});
if (!good.success || !equal.success || bad.success || bad.error.issues[0].path[0] !== 'end') throw Error('Unexpected span result');
console.log({forward:good.success,equal:equal.success,backward:bad.success,path:bad.error.issues[0].path});
Tools
Tools frequently paired with this sample
Related
Related sample collections
Related