feature request: zod.fallback() and zod.catch()
See original GitHub issuezod is awesome!
Maybe this is already possible, but often I need more granular control of safeParse
-like behavior… Something like:
const color = string().fallback('#000000');
const person = object({ name: string(), age: number() }).fallback({});
Or, maybe with more granular control (e.g. have the fallback be based on a ZodError
):
const person = object( {name: string(), age: number() }.catch(err => { console.error(err.message); return {} );
(so .fallback(foo)
is just .catch(() => foo)
).
Thanks for listening/considering!
ps: some of this might be doable with any().transform(val => xxx).string()
but seems super hacky and non zod-like since
you basically have to use JS/TS to coerce the value…
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:7 (1 by maintainers)
Top Results From Across the Web
conform-to/zod - NPM Package Overview - Socket.dev
Start using Socket to analyze @conform-to/zod and its 0 dependencies ... The resolve(schema).validate API is also replaced by validate() :.
Read more >express-zod-api - npm
A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.
Read more >Colin McDonnell (@colinhacks) / Twitter
Zod 3.20 is here! This is a big one. `z.coerce` `.pipe()` `.catch()` `z.symbol()` `z.number().finite()` `z.string().datetime()` ...
Read more >Validating Input with Zod in TypeScript - Morioh
Don't worry we will get to more complicated validations later in this article. All you need to do is: Import Zod; Create a...
Read more >Validating Remix Form Data Using Zod and TypeScript in ...
You can use Zod to validate form input and create typed TypeScript objects ... The FormData that remix is posting with the request...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
In case anyone comes across this in the future, here’s an even better (IMHO) approach which does not involve
safeParse
etc.:Awesome @colinhacks. Totally agree about keeping out of core… Feel free to close this whenever you like!
Just to clarify my OP, the fallback value isn’t always compatible with
Schema<T>
. I’ve found this idiom most useful when I want to read an array of values (e.g. firestore records) but be tolerant of bad values: