Search code examples
reactjstypescriptformsreact-hook-formzod

How to make a custom error message in zod?


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')}</}

Solution

  • 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))
        }