DT
Drizzle Team•13mo ago
zeekrey

Custom error messages with drizzle-zod?

Hey there! 👋 Does somebody know how to add custom error messages to a schema created via createInsertSchema? I know I can refine the schema by passing an object as the second argument, but since the error messages are part of the actual type definition, I would be repeating myself like so:
export const users = sqliteTable("users", {
id: integer("id").primaryKey().notNull()
});

const zodSchema = createInsertSchema(users, {
id: (schema) => schema.id.number({
required_error: "Id is required",
invalid_type_error: "Id must be a number",
});
export const users = sqliteTable("users", {
id: integer("id").primaryKey().notNull()
});

const zodSchema = createInsertSchema(users, {
id: (schema) => schema.id.number({
required_error: "Id is required",
invalid_type_error: "Id must be a number",
});
4 Replies
zeekrey
zeekreyOP•13mo ago
I would like to add another thing: createInsertSchema creates a Zod schema that uses ZodNullable (since all non-required fields could be null). However, this requires you to modify the schema again because it's not possible to use this schema with any input (since null cannot be assigned to an input). What is the best way to handle this? To solve these issues, I currently overwrite almost any field since I need a) a custom error message or b) need to convert null to undefined. 😥
Angelelz
Angelelz•13mo ago
Such is the life of a developer when trying to combine front end and back end I'm not familir with drizzle-zod, is this how you do it or is this how you're proposing that should be done?
zeekrey
zeekreyOP•13mo ago
This is how I do it at the moment, but it feels bad since I overwrite the schema to make it form compatible 😂. I'm looking for a way to: a) Add custom Zod error messages without the need to rewrite the type. b) Remove null from the type. I found schema.transform, but this runs after validation, so it can't be used to inherit a type for validation.
Angelelz
Angelelz•13mo ago
Isn't there a schema.refine?
Want results from more Discord servers?
Add your server