Home > Back-end >  Yup - How to conditionally validate at least one of n values are set?
Yup - How to conditionally validate at least one of n values are set?

Time:01-21

How to use Yup validation to make the field mandatory if 1 of the other 3 fields are not empty? I tried the following schema but got cyclic dependency issue. Thank you!

const schema = yup.object().shape({
  a: yup.string().when(['b', 'c', 'd'], {
    is: (b, c, d) => !b && !c && !d,
    then: yup.string().required()
  }),
  b: yup.string().when(['a', 'c', 'd'], {
    is: (a, c, d) => !a && !c && !d,
    then: yup.string().required()
  }),
  c: yup.string().when(['a', 'b', 'd'], {
    is: (a, b, d) => !a && !b && !d,
    then: yup.string().required()
  }),
  d: yup.string().when(['a', 'b', 'c'], {
    is: (a, b, c) => !a && !b && !c,
    then: yup.string().required()
  })
}, [['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']]) 

CodePudding user response:

You can this: a: yup.string().when(['b', 'c', 'd'], { is: (...fields) => fields.some((field) => field === true), then: yup.string().required() }),

You can use the function of JS but I chose 'some' that checks if there are at least one of the items in the array that match the condition, which is equivalent to your check - if even not one item in the array is true that's the same like all of them false.

By the way, what is the dependencies array for? [['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']]) I don't think it's mentioned in the Yup official docs (at least as I know if there is a reason i'll be happy to get updated, thanks).

CodePudding user response:

Hopefully the Below code will solve your problem

/* 
   All you need to do is list all the pair-wise (2-tuples) combinations. 
   As you have 4 fields, you expect to have 6 pairs in your array. 
   i.e. ['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'])
*/

const schema = yup.object().shape({
  a: yup.string().when(['b', 'c', 'd'], {
    is: (b, c, d) => b || c || d,
    then: Yup.string(),
    otherwise: Yup.string().required('Required')
  }),
  b: yup.string().when(['a', 'c', 'd'], {
    is: (a, c, d) => a || c || d,
    then: Yup.string(),
    otherwise: Yup.string().required('Required')
  }),
  c: yup.string().when(['a', 'b', 'd'], {
    is: (a, b, d) => a || b || d,
    then: Yup.string(),
    otherwise: Yup.string().required('Required')
  }),
  d: yup.string().when(['a', 'b', 'c'], {
    is: (a, b, c) =>  a || b || c,
    then: Yup.string(),
    otherwise: Yup.string().required('Required')
  })
}, [['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'] ])

More Details Check this link

  •  Tags:  
  • Related