Z
Zod3mo ago
adxvcasas

adxvcasas - How to set a default value for opti...

How to set a default value for optional values? Hello, so I'm trying to set a default value for my schema, is this approach acceptable?
const formSchemaData = z.object({
dryRunDate: z.string().optional().default('none'),
})
const formSchemaData = z.object({
dryRunDate: z.string().optional().default('none'),
})
2 Replies
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Scott Trinh
Scott Trinh3mo ago
(note that this only works to set a default if you pass it undefined which is not typical for most form libraries) you might end up needing:
const formSchemaData = z.object({
dryRunDate: z.union([z.literal("").transform(() => "none"), z.string().min(1)]),
})
const formSchemaData = z.object({
dryRunDate: z.union([z.literal("").transform(() => "none"), z.string().min(1)]),
})
Which transforms the literal empty string into the string "none", while passing through any other non-empty strings.
Want results from more Discord servers?
Add your server
More Posts