javascriptzod

How do I add validation conditions to optional fields?


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.


Solution

  • Came across a solution that works. Basically just replace the optional property with .or(z.literal('')) on the optional fields, like so:

    phone: z.string().min(10, "Type a complete number.").or(z.literal('')),
    email: z.string().email({ message: "Type a valid email address." }).or(z.literal('')),
    website: z.string().url('Please type a valid website (include http/https)').or(z.literal(''))
    

    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