I have a phone, email and website fields in my form that are optional. But if the user decides to fill them I want to validate that the input is a valid phone, email and url. This is how I have the fields in my schema:
phone: z.string().min(10, "Type a complete number.").optional(),
email: z.string().email({ message: "Type a valid email address." }).optional(),
website: z.string().url('Please type a valid website (include http/https)').optional(),
However even while being marked as optional zod is treating them as required. How would I set it up so that these fields are optional so that the user can leave them empty but if they decide to fill them it validates accordingly?
Thanks in advance.
2
Answers
Came across a solution that works. Basically just replace the optional property with
.or(z.literal(''))
on the optional fields, like so:Now it works as intended allowing the user to leave the fields empty but validating them if the user fills them.
Found the solution here: https://github.com/colinhacks/zod/issues/310
An empty string or null value is not valid. Zod’s optional means either it must be validated as a string, or it has to be undefined.
You could try:
This would make the validated output either be a string, or null.