Best practice for accepting numbers in query params #754
-
If I want to accept a number as a query parameter (for example, I also tried the following: z
.preprocess(
value =>
typeof value === 'string' ? Number.parseInt(value) : undefined,
z.number().int().min(1).max(100),
) This works, but the generated OpenAPI schema is strange...
...and confuses code generators and documentation portals (note the Is there a better way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The problem with the query params is that they're always strings. Try this, should work fine: z.string()
.trim().regex(/\d+/)
.transform((id) => parseInt(id, 10)) In the latest version (that has zod v3.20), also the following possible: z.string().regex(/\d+/).pipe(
z.number({ coerce: true }).int().positive()
); |
Beta Was this translation helpful? Give feedback.
-
👍🏽
Numeric string, if you also add
Nice. That should also be fine.
You can add more validations into it: |
Beta Was this translation helpful? Give feedback.
The problem with the query params is that they're always strings.
I believe that the best way would be describe it as a numeric string, that has a transformation into number.
Try this, should work fine:
In the latest version (that has zod v3.20), also the following possible:
@shroudedcode