drizzle-zod refine enum
Here's my users table and the schema generated with
drizzle-zod
that I want to modify. As you can see, the role column is an enum, but I want to modify the error message as I did with email and password. I've tried several solutions but nothing works, could you help me?
2 Replies
I think schema.role.describe does that, I'm not sure tho
I couldn't get schema.<field>.describe to do anything. I wound up with (using @Cetus 🔛🔝's example)
...
role: () => z.enum(['USER', 'ADMIN'], { required_error: "Please select a role" }), //in createInsertSchema
...
But this feels like I'm completely redefining the schema which I don't love. For example, I could do the following and have a mismatch between the schema and table definition.
role: () => z.enum(['USER', 'ADMIN', 'NEW-SUPER-ADMIN'], { required_error: "Please select a role" }),
I'd prefer (or something like)
role: (schema) => schema.role.notNull({ required_error: "Please select a role" }),
Since then the valid values couldn't change.
The above mismatch is removed if you refactor a little.
export const roleTypes = ["USER", "ADMIN"] as const; // defined anywhere
...
role: mysqlEnum("role", roleTypes).notNull(), // in createTable
...
role: () => z.enum(roleTypes, { required_error: "Please select a role" }), // in createInsertSchema
-zd