Create object from Zod object with defaults but that will not pass its validation #2487
andredewaard
started this conversation in
Ideas
Replies: 1 comment
-
const EmailForm = z.object({
email: z.string().email().default(''),
})
EmailForm.parse({}) //=> ZodError: Invalid email
EmailForm.parse({ email: undefined }) //=> ZodError: Invalid email
EmailForm.parse({ email: 'gibberish' }) //=> ZodError: Invalid email
EmailForm.parse({ email: '[email protected]' }) //=> { email: "test@test.com" } A union works and is quite legible ("accept an email string, or accept const EmailForm = z.object({
email: z.union([z.string().email(), z.undefined().transform(() => '')]),
})
EmailForm.parse({}) //=> { email: "" }
EmailForm.parse({ email: undefined }) //=> { email: "" }
EmailForm.parse({ email: '[email protected]' }) //=> { email: "test@test.com" }
EmailForm.parse({ email: 'gibberish' }) //=> ZodError: Invalid email Things that I tried but that didn't work:
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is it possible to create an object from a Zod object with defaults BUT that will not pass its validation?
So for example i have
But when i want to validate that the object has an correct email, This should fail
Beta Was this translation helpful? Give feedback.
All reactions