Custom Error Message For Object #868
-
I'm using So when the user clears the autocomplete value it will be set to null by the autocomplete. In this case i want to print out the error message that this field is required. What i'm getting now is the generic error message:
Here is my schema: const projectSchema = z.object({
id: z.string().uuid(),
name: translationSchema,
start: z.string(),
end: z.string().nullable(),
});
export const ti8mProjectSchema = z.object({
project: projectSchema,
}); So is there a way to define a custom error message to show when the field gets the Thx in advance and keep up the great work!!! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Hm, this is a slightly odd one, since you want the inferred type to be able to be null (so you can let the autocomplete set it to null without TS barking up the wrong tree), but let the validation fail if it is. This should do the trick: import { z } from 'zod';
const schema = z
.object({ hm: z.boolean() })
.nullable()
.refine((x) => x !== null, 'pls no null 😿');
type Type = z.infer<typeof schema>;
//type Type = {
// hm: boolean;
//} | null
schema.parse(null);
//ZodError: [
// {
// "code": "custom",
// "message": "pls no null 😿",
// "path": []
// }
// ] |
Beta Was this translation helpful? Give feedback.
-
Here's 1 way to do it. const projectSchema = z.object( {
id: z.string().uuid(),
name: translationSchema,
start: z.string(),
end: z.string().nullable(),
}, {
errorMap: ( issue, ctx ) => {
if ( ctx.data === null ) return { message: 'custom errorMap message' }
return { message: ctx.defaultError }
}
} )
const result = projectSchema.safeParse( null )
!result.success && result.error.formErrors.formErrors[ 0 ] // 'custom errorMap message'
What do you mean by this? |
Beta Was this translation helpful? Give feedback.
Here's 1 way to do it.
What do you mean by this?