Zod optional fields and numbers

I'm following along with the T3 app video made a few weeks ago (the twitter clone one), but adjusting it for an app I'm making. I'm currently creating a page that sets up Organizations (teams), but I can't figure out how to resolve this issue (I've watched a handful of Zod, tRPC, and Typescript videos and read through some other threads to try and find an answer, but I haven't found anything to solve this yet). Here is my current schema:
orgId: z.number().min(1).max(191),
name: z.string().min(1).max(191),
nickname: z.string().min(1).max(191).optional(),
parentOrgId: z.number().min(1).max(191).optional()
orgId: z.number().min(1).max(191),
name: z.string().min(1).max(191),
nickname: z.string().min(1).max(191).optional(),
parentOrgId: z.number().min(1).max(191).optional()
But I was getting an error, and learned that inputs can only by strings, so I tried converting the orgId with parseInt, but that doesn't work for the parentOrgId field if I leave it blank (since it returns NaN instead of undefined), and if I leave nickname blank it also returns an error because it's just a blank string and not undefined (I think in Zod it has to either match the content needed or be undefined as part of the optional argument). Sorry if I'm not making sense, I'm happy to share more of my code if needed, but I'd really appreciate help figuring this out!
2 Replies
Matvey
Matvey2y ago
use z.coerce.number() instead of z.number(). It will accept strings and convert them into numbers
.ketchikan
.ketchikanOP2y ago
Oh good thinking! I tried that out, but I'm getting an error on the button:
<button
onClick={() =>
mutate({
albatrossOrgId: albatrossID,
name: orgName,
nickname: nickname,
parentOrgId: parentOrg,
})
}
type="submit"
className="border border-black bg-blue-400 "
>
<button
onClick={() =>
mutate({
albatrossOrgId: albatrossID,
name: orgName,
nickname: nickname,
parentOrgId: parentOrg,
})
}
type="submit"
className="border border-black bg-blue-400 "
>
The error is on albatrossOrgId and parentOrgId (both of which I added that coerce), it's a typing error, it's expecting numbers but getting a string still I reset ts just in case, but it looks like it's persisting Oh I may have just figured it out! Let me know if this is a bad solution:
<button
onClick={() =>
mutate({
albatrossOrgId: parseInt(albatrossID),
name: orgName,
nickname: nickname || undefined,
parentOrgId: parseInt(parentOrg) || undefined,
})
}
type="submit"
className="border border-black bg-blue-400 "
>
<button
onClick={() =>
mutate({
albatrossOrgId: parseInt(albatrossID),
name: orgName,
nickname: nickname || undefined,
parentOrgId: parseInt(parentOrg) || undefined,
})
}
type="submit"
className="border border-black bg-blue-400 "
>
Thank you for your help!
Want results from more Discord servers?
Add your server