Skip to content

v4: z.file optional not working #4125

Closed
@l0uisgrange

Description

@l0uisgrange

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\""
                  ]
             }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions