Replies: 4 comments 16 replies
-
You can achieve it with z.preprocess(
a => parseInt(z.string().parse(a), 10),
z.number()
); Though, I'd like to see something a bit less verbose and cumbersome to achieve the same. Something like |
Beta Was this translation helpful? Give feedback.
-
I too was quite surprised that parsing from strings is not a built-in feature. What made this whole experience way more annoying was that (I even tried create a subclass of ZodNumber that overwrites its |
Beta Was this translation helpful? Give feedback.
-
Hello, I also need this to parse numbers and booleans searchParams which are always parsed as strings. Thanks |
Beta Was this translation helpful? Give feedback.
-
Use Below also addresses the comment from @killercup
const positiveNumberFromStringOrNumber = z.preprocess(
input => {
if ( typeof input === 'number' ) return input
if ( typeof input === 'string' ) return parseFloat( input )
},
z.number().gt( 0 ) // you can add string validators here
)
console.log( positiveNumberFromStringOrNumber.safeParse( 1 ).success ) // true
console.log( positiveNumberFromStringOrNumber.safeParse( '1' ).success ) // true
console.log( positiveNumberFromStringOrNumber.safeParse( 0 ).success ) // false
console.log( positiveNumberFromStringOrNumber.safeParse( '0' ).success ) // false
console.log( positiveNumberFromStringOrNumber.safeParse( -1 ).success ) // false
console.log( positiveNumberFromStringOrNumber.safeParse( '-1' ).success ) // false |
Beta Was this translation helpful? Give feedback.
-
In the spirit of parse, don't validate, I'd like Zod to return a number for
z.number().parse("42")
instead of throwing an error. I'd like the same for booleans, arrays, objects, basically anything that has a well adopted string representation via JSON as well as widely accepted formats like ISO date strings.I want to be able to use Zod for parsing, not validating, incoming requests from a client and I want my server to be conservative in what it sends back to the client but be liberal in what it accepts (robustness principle).
Beta Was this translation helpful? Give feedback.
All reactions