Skip to content

Best practice for accepting numbers in query params #754

Answered by RobinTail
niklashigi asked this question in Q&A
Discussion options

You must be logged in to vote

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:

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()
);

@shroudedcode

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@niklashigi
Comment options

Answer selected by RobinTail
Comment options

You must be logged in to vote
1 reply
@niklashigi
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants