Z
Zod•4w ago
unnreaal

unreal - Hello, i have this schema tsconst som...

Hello, i have this schema
const someSchema = z.object({
description: z
.string()
.min(20, 'Min description length is 20')
.max(50, 'Max description length is 50')
.nullable()
.optional(),
});
const someSchema = z.object({
description: z
.string()
.min(20, 'Min description length is 20')
.max(50, 'Max description length is 50')
.nullable()
.optional(),
});
and the guy of the front-end is sending { description: null }, but zod is giving me the error of the image, any ideia?
No description
5 Replies
tristinDLC
tristinDLC•4w ago
The issue is that the .nullable() and .optional() methods are being applied to the value associated with the "description" key only. The original z.object() that's wrapping your keys is still required to be provided to properly validate. Here is the code that works based on your schema above:
import { z } from 'zod'

const someSchema = z.object({
description: z
.string()
.min(20, 'Min description length is 20')
.max(50, 'Max description length is 50')
.nullable()
.optional(),
})

someSchema.parse({ description: null }) // { description: null }
import { z } from 'zod'

const someSchema = z.object({
description: z
.string()
.min(20, 'Min description length is 20')
.max(50, 'Max description length is 50')
.nullable()
.optional(),
})

someSchema.parse({ description: null }) // { description: null }
Scott Trinh
Scott Trinh•4w ago
wait... isn't that the same thing? The OP schema absolutely should be able to parse { description: null }
import assert from "node:assert/strict";
import { z } from "zod";

const schema = z.object({
description: z.string().nullable().optional(),
});

assert.ok(schema.safeParse({ description: null }).success);
console.log("ok");
import assert from "node:assert/strict";
import { z } from "zod";

const schema = z.object({
description: z.string().nullable().optional(),
});

assert.ok(schema.safeParse({ description: null }).success);
console.log("ok");
tristinDLC
tristinDLC•4w ago
@Scott Trinh Wow, I misread OP. I missed the curly braces originally and understood the problem to be that only null was being sent. That's my mistake. Looks like I need a nap haha
Scott Trinh
Scott Trinh•4w ago
It's usually me that transposes some issue like that, so no worries at all 😅
janglad
janglad•4w ago
yea this def should work @unreal are you using this schema directly? Or is it used in another schema
Want results from more Discord servers?
Add your server