ahols
ahols

Reputation: 133

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.

Upvotes: 0

Views: 350

Answers (2)

Zxeenu
Zxeenu

Reputation: 872

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:

phone: z.string().nullable().default(null)

This would make the validated output either be a string, or null.

Upvotes: 0

ahols
ahols

Reputation: 133

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

Upvotes: 0

Related Questions