Last active
July 24, 2024 09:15
-
-
Save bennettdams/463c804fcfde0eaa888eaa4851c668a1 to your computer and use it in GitHub Desktop.
Zod empty string transformed to `undefined` including handling optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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