Skip to content

Instantly share code, notes, and snippets.

@bennettdams
Last active April 3, 2024 16:20
Show Gist options
  • Save bennettdams/463c804fcfde0eaa888eaa4851c668a1 to your computer and use it in GitHub Desktop.
Save bennettdams/463c804fcfde0eaa888eaa4851c668a1 to your computer and use it in GitHub Desktop.
Zod empty string transformed to `undefined` including handling optional
import { z } from 'zod'
const emptyStringToUndefined = z.literal('').transform(() => undefined)
/**
* Provide a schema and get a schema that is optional and empty strings are transformed to `undefined`.
* When someone removes his input of this field, the then empty string is transformed to `undefined`.
*
* Example:
*
* A password field that is either filled with minimum 5 characters. If it is not filled,
* it is "valid" as well, because it is `undefined` via the `transform`:
*
* `password: asOptionalStringWithoutEmpty(z.string().min(5)),`
*
* Imagine inputs in this order:
*
* | INPUT | VALUE | VALID? |
* | :--------------- | :------------------ | :------------------ |
* | -nothing- | undefined | no
* | a | a | no
* | bcdef | abcdef | yes (is min. 5)
* | -def | abc | no
* | -abc | "" -> undefined | yes (is undefined)
*/
export function asOptionalStringWithoutEmpty<T extends z.ZodString>(schema: T) {
return schema.optional().or(emptyStringToUndefined)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment