TripleSpeeder
TripleSpeeder•15mo ago

verify Table ID type in a form with zod

I want to submit an id of convex type Id<"part"> with a form. I'm doing form validation with zod and wondering what is the best way to do this. If i use z.string() for the part ID, typescript complains that string can not be assigned to Id<"part"> when calling the mutation function. This sounds reasonable, as the mutation indeed expects an argument of type Id<"part">. I get correct types and no typescript error when using z.custom<Id<"part">>() to validate the field. But I think I still need to add a validator function to this custom type, because zod says If you don't provide a validation function, Zod will allow any value. I can add a manual check to make sure the provided value is indeed a string, and maybe check length and whatnot. But I'm wondering if I'm missing something here... Is there a best practice for a scenario like this?
3 Replies
sshader
sshader•15mo ago
Here's an example of a zod validator that validates that the value is a string, and casts it to Id<"myTable"> https://github.com/get-convex/convex-helpers/blob/a6b19af85bb4c4ed5ef11b2519ef51ef4bd41f3c/convex/lib/withZod.ts#L18 Currently, it's not possible to check if a string is an ID from a specific table outside of a Convex function (v.id("myTable") in an arg validator or checking db.normalizeId("myTable", myId) is not null), so the best you can do for validating input on the client is to check that the value is a string (we've thought about adding a function to validate that something matches our ID format, or one day adding the ability to validate that a string is an ID from a particular table from client code). Does this help?
GitHub
convex-helpers/convex/lib/withZod.ts at a6b19af85bb4c4ed5ef11b2519e...
A collection of useful code to complement the official packages. - get-convex/convex-helpers
TripleSpeeder
TripleSpeederOP•15mo ago
Yeah, sounds good! Thank you 🙂
ian
ian•13mo ago
Here's a new zod validator that does the full v.id checking for argument validation: https://stack.convex.dev/typescript-zod-function-validation
Using Zod with TypeScript for Server-side Validation and End-to-End...
Use Zod with TypeScript for argument validation on your server functions allows you to both protect against invalid data, and define TypeScript types ...