Skip to content

v4: z.file optional not working #4125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
l0uisgrange opened this issue Apr 12, 2025 · 0 comments
Open

v4: z.file optional not working #4125

l0uisgrange opened this issue Apr 12, 2025 · 0 comments

Comments

@l0uisgrange
Copy link

l0uisgrange commented Apr 12, 2025

Hi,

I'm a huge Svelte and Zod fan, and I think my only problem with Zod is that it doesn't manage well formData empty values.

For example, here are empty inputs formData values :

Input type FormData
file File { size: 0, type: 'application/octet-stream', name: '', lastModified: ... }
text ""

And hence the .optional() does not work as the value is not null.

I think the best workaround would be to seriously consider something like z.file().mime(...).formOptional() which would try if the file has empty values.

Note that I tried the following schema for a text field, but it does not generate any errors.properties that I could reuse in my Svelte views.

z.url().or(z.string().length(0, { error: 'Invalid URL' }).nullish())

Here is another example with the file input :

const schema = z.object({
    status: z.enum(['accepted', 'created', 'refused', 'cancelled']),
    organisation: z.string().nonempty(),
    logo: z.file().mime(['image/png', 'image/webp', 'image/svg+xml', 'image/jpeg']).max(1_000_000_000).optional(),
});

and the z.file().optional() does not seem to work, because it throws the error :

"properties": {
    "logo": {
        "errors": [],
        "properties": {
             "type": {
                  "errors": [
                      "Invalid option: expected one of \"image/png\"|\"image/webp\"|\"image/svg+xml\"|\"image/jpeg\""
                  ]
             }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant