8

Imagine I have an object like

{
  field1: 'test',
  field2: 'test1'
}

How I can create the following validation:

If field1 and field2 both are empty - it is not valid

If field1 and field2 both are not empty - it is not valid

Other cases are valid.

Kirill Novikov
  • 2,576
  • 4
  • 20
  • 33
  • `type T = {field1: string, field2?: never} | {field1?: never, field2: string};` XORs two types together, I havent used ZOD though so I dont know if thats what you need. – EDD Feb 26 '23 at 13:24

1 Answers1

12

you can use .refine()

const res = z.object({
field1: z.string().optional(),
field2: z.string().optional(),
}) 
.refine(schema => (schema.field1===undefined && schema.field2===undefined 
|| schema.field2!==undefined && schema.field1!==undefined) ? false :true, 
{
message: 'your message'
})

more info here

Maciej Dębiec
  • 136
  • 1
  • 4
  • FYI, you don't need to use a ternary, just use your expression and it will result in true or false. eg: `refine(schema => schema.field1 === undefined)` – Soviut Aug 16 '23 at 22:03