Published on

zod

Authors
  • avatar
    Name
    Timothy Blanks

https://zod.dev/

First name or last name can be blank, the z.literal('') is used when field is dirty to allow it to be cleared

.superRefine(...)

Is used to make both first and last name fields to be required if either is populated

const nameSchems = z
  .object({
    first: z.string().min(3).or(z.literal('')),
    last: z.string().min(3).or(z.literal('')),
  })
  .superRefine((fields, ctx) => {
    // if fields is null just quit
    if (!fields) return
    const { first, last } = fields
    if (first || last) {
      if (!first) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: 'Required',
          path: ['first'],
        })
      }
      if (!last) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: 'Required',
          path: ['last'],
        })
      }
    }
  })