Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZOD validation based on another field [duplicate]

Tags:

zod

typescript

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.

like image 484
Kirill Novikov Avatar asked Nov 28 '25 06:11

Kirill Novikov


1 Answers

You can use .refine():

const res = z.object({
    field1: z.string().optional(),
    field2: z.string().optional(),
}) 
    .refine(schema => {
        return !(
            schema.field1 === undefined && 
            schema.field2 === undefined ||
            schema.field2 !== undefined && 
            schema.field1 !== undefined
        ); 
    }, "Your message");
like image 53
Maciej Dębiec Avatar answered Nov 29 '25 20:11

Maciej Dębiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!