Skip to content

Custom Error Message For Object #868

Answered by JacobWeisenburger
knoefel asked this question in Q&A
Discussion options

You must be logged in to vote

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'

...but i don't want to set it global, just for the desired fields.

What do you mean by this?

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@knoefel
Comment options

@StefanTerdell
Comment options

Comment options

You must be logged in to vote
1 reply
@knoefel
Comment options

Answer selected by knoefel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants