Search code examples
reactjsreact-hook-formyup

YUP validation of array of object where at least one value is true


I started using Yup with react-hook-form, but I have some problems.

Actually I have a watcher that sets at the start an array of objects:

[
    {
        "code": "english",
        "value": 0
    },
    {
        "code": "french",
        "value": 0
    },
    {
        "code": "german",
        "value": 0
    },
    {
        "code": "italian",
        "value": 0
    }
]

I need to validate that at least 1 value must be true or 1. Any help is appreciated.


Solution

  • If someone else will need, I did this (for sure there will be a better way), but this working in my case...

    Yup.array()
            .of(
              Yup.object().shape({
                value: Yup.boolean(),
              }),
            )
            .test({
              name: 'one-true',
              message: 'Required',
              test: (val) => !every(val, ['value', false]),
            }),