I’m using Yup to validate 3 fields which are all dependent on each other.
fieldA
, fieldB
and fieldC
. They are numbers and at least one of them needs to have a value > 0.
I’m trying to solve it like this:
JavaScript
x
31
31
1
myFields: Yup.object().shape(
2
{
3
fieldA: Yup.number().when(['fieldB', 'fieldC'], {
4
is: (fieldB, fieldC) =>
5
fieldB < 1 && fieldC < 1,
6
then: Yup.number().min(
7
1,
8
'some error message'
9
),
10
}),
11
fieldB: Yup.number().when(['fieldA', 'fieldC'], {
12
is: (fieldA, fieldC) =>
13
fieldA < 1 && fieldC < 1,
14
then: Yup.number().min(
15
1,
16
'some error message'
17
),
18
}),
19
fieldC: Yup.number().when(['fieldB', 'fieldA'], {
20
is: (fieldB, fieldA) =>
21
fieldB < 1 && fieldA < 1,
22
then: Yup.number().min(
23
1,
24
'some error message'
25
),
26
}),
27
28
},
29
['fieldA', 'fieldB', 'fieldC']
30
),
31
This worked fine with only 2 fields fieldA
and fieldB
, where each one only had the other field passed in when(...
but since introducing a third field, I now have a cyclic dependency. Do I need a completely different approach, ie. an external validation function or am I missing some detail here?
Advertisement
Answer
Your dependencies array is wrong, needs to be [[string, string]], hence you cannot bind all 3 of your fields inside. You have to do it in combinations as
[['fieldA', 'fieldB'], ['fieldA', 'fieldC'], ['fieldB','fieldC']]