Reputation: 11
I'm trying to validate that an array has 2 specific values, something like:
['foo', 'bar']
I feel like the closest I came to the answer is something like this:
Yup.array()
.of(Yup.mixed().oneOf(['foo', 'bar']))
.min(2)
.max(2)
But this would also pass ['foo', 'foo']
and ['bar', 'bar']
Upvotes: 1
Views: 1298
Reputation: 8857
As a variant you can use Yup test
function, which allow you to manipulate with current field value and another form field values. On this example we check is field value has duplicates like ['foo', 'foo']
and then check if there are no duplicated or every value of field array includes foo
or bar
:
Yup.array()
.test('contains', 'Error message here', function (value) {
let hasDuplicate = value.some((val, i) => value.indexOf(val) !== i);
return !hasDuplicate && value.every(el => ['foo', 'bar'].includes(el));
})
.min(2)
.max(2)
Here you can find more insformcation about test
function: https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
Upvotes: 1
Reputation: 170
you can write a function for this too. what i understood is you are looking for exactly 2 variables in an array. here is what i tried
function find(arr,first,second){
let temp=false;
if(arr.includes(first)&&arr.includes(second)){
temp=true;
}
return temp;
}
find(["foo","bar"],"foo","bar");
if you are looking for an array of exactly same length then you can have length check too in function. the function will look like
function find(arr,first, second){
let temp=false;
if(arr.length!=2)
return false
if(arr.includes(first)&&arr.includes(second)){
temp=true;
}
return temp;
}
find(["foo","bar"],"foo","bar");
Upvotes: 0