How to make a custom error message in zod?
Asked Answered
M

2

10

I'm trying to write a custom error message for zod validation.

This is my schema object, which I passed in the error message.

const schema: ZodType<FormData> = z.object({
    firstName: z.string().nonempty(),
    lastName: z.string().nonempty(),
    email: z.string().email().min(5).nonempty(),
    pin: z.string( { invalid_type_error: "Must contain 4 digitsss "}).nonempty().min(4, "Must be 4 digits").max(4, "Must be 4 digits").regex(pinPattern),
    phoneNumber: z.string().nonempty().min(11),
    password: z.string().min(8).regex(Passwordregex).nonempty(),
    confirmPassword: z.string().min(8).nonempty(),
  }).refine(data => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword']
  })

enter image description here

I've tried the string replace method, but I'm not getting my desired result.

 {errors.
<span className='text-xs font-medium text-[#DC2626]'>{errors.firstName.message?.replace('String', 'First Name')}</}
Midweek answered 30/3, 2023 at 0:0 Comment(1)
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Harney
S
8
import { ZodError, ZodIssue } from 'zod'

const formatZodIssue = (issue: ZodIssue): string => {
    const { path, message } = issue
    const pathString = path.join('.')

    return `${pathString}: ${message}`
}

// Format the Zod error message with only the current error
export const formatZodError = (error: ZodError): string => {
    const { issues } = error

    if (issues.length) {
        const currentIssue = issues[0]

        return formatZodIssue(currentIssue)
    }
}

And wrap your validations code in trycatch statement:

 try {
      ...your code here  
    } catch (error) {
        console.error(error)
        throw new Error(formatZodError(error))
    }
Statocyst answered 8/7, 2023 at 10:58 Comment(0)
C
12

You can use a custom message in zod by passing an object with the structure { message: "Custom error message here" } as an argument.

Note that in newer versions of Zod, nonempty() is deprecated, and you should instead use min(1) Source.

In your code above, to show an error that the First Name is required can be accomplished as follows:

const schema: ZodType<FormData> = z.object({
  firstName: z.string().min(1, { message: "First Name is required" })
});

If your field has a requirement for a minimum number of characters, you can chain a second .min() with the min number and respective error message if user enters less characters as the arguments.

Calipee answered 16/12, 2023 at 23:49 Comment(0)
S
8
import { ZodError, ZodIssue } from 'zod'

const formatZodIssue = (issue: ZodIssue): string => {
    const { path, message } = issue
    const pathString = path.join('.')

    return `${pathString}: ${message}`
}

// Format the Zod error message with only the current error
export const formatZodError = (error: ZodError): string => {
    const { issues } = error

    if (issues.length) {
        const currentIssue = issues[0]

        return formatZodIssue(currentIssue)
    }
}

And wrap your validations code in trycatch statement:

 try {
      ...your code here  
    } catch (error) {
        console.error(error)
        throw new Error(formatZodError(error))
    }
Statocyst answered 8/7, 2023 at 10:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.