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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With