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?
export const roleEnum = pgEnum('role', ['USER', 'ADMIN'])

export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', {
length: 256,
})
.unique()
.notNull(),
password: varchar('password', {
length: 256,
}).notNull(),
role: roleEnum('role').notNull(),
})

export const insertUserSchema = createInsertSchema(users, {
email: schema => schema.email.email("Format de l'adresse email incorrect"),
password: schema => schema.password.min(8, "Le mot de passe doit contenir au moins 8 caractères"),
})
export const roleEnum = pgEnum('role', ['USER', 'ADMIN'])

export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', {
length: 256,
})
.unique()
.notNull(),
password: varchar('password', {
length: 256,
}).notNull(),
role: roleEnum('role').notNull(),
})

export const insertUserSchema = createInsertSchema(users, {
email: schema => schema.email.email("Format de l'adresse email incorrect"),
password: schema => schema.password.min(8, "Le mot de passe doit contenir au moins 8 caractères"),
})
2 Replies
Cyber Grandma
Cyber Grandma12mo ago
I think schema.role.describe does that, I'm not sure tho
zd
zd3mo ago
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
Want results from more Discord servers?
Add your server