I want to create an object which can have several keys. Two keys however depend on each other, until and count. Both of these are optional. However if one is provided, the other shouldn't be.
Is this XOR possible?
const schema = yup.object({
count: yup.number(),
until: yup.date()
});
Yup, I'm not sure if there is a better way of doing it but this works.
``const schema = yup
.object({
count: yup.number(),
until: yup.date(),
})
.test('xor',object should have count or until`, val => {
return !!val.count !== !!val.until
})
console.log(schema.isValidSync({}))
console.log(schema.isValidSync({count: 3}))
console.log(schema.isValidSync({until: new Date()}))
console.log(schema.isValidSync({count: 4, until: new Date()}))
```
There are better ways of writing the test function given in the documentation if you're interested.
This is very cool thanks for sharing @schafer14 !
Most helpful comment
Yup, I'm not sure if there is a better way of doing it but this works.
``
const schema = yup .object({ count: yup.number(), until: yup.date(), }) .test('xor',object should have count or until`, val => {return !!val.count !== !!val.until
})
console.log(schema.isValidSync({}))
console.log(schema.isValidSync({count: 3}))
console.log(schema.isValidSync({until: new Date()}))
console.log(schema.isValidSync({count: 4, until: new Date()}))
```
There are better ways of writing the
testfunction given in the documentation if you're interested.