'Yup (with formik and react) - Can't validate array length

kinda new to Yup and I can't figure out how to validate that an array is not empty.

I'm using react + formik + yup + material-ui

here is an example I've created:

https://codesandbox.io/s/new-fire-29onf?file=/src/App.js

I tried in the validationSchema to just use the required method:

validationSchema={Yup.object({ permissions : Yup.array().required('permission cant be empty') })}

i tried to add my functionally using the test method like this:

validationSchema={Yup.object({ permission: Yup.array().test ('notEmptyArr', 'array is empty', (value) =>{ console.log(value); return value.length > 0; }) })}

i also tried to add method to the array like this:

Yup.addMethod(Yup.array, "notEmpty", function(message) { return this.test("notEmpty", message, function(arr) { return Boolean( arr.length > 0 ); }); });

But none of that worked for me : (

if I remove the validation I see the value.permission is indeed an array, with values (if selected)

what am I doing wrong?

thanks



Solution 1:[1]

You can use .min():

validationSchema={Yup.object({
    permissions: Yup.array().min(1)
})}

Solution 2:[2]

UPDATE / WARNING:

Previously only array().required() was required to make sure there was at leas 1 item in the array. For example [] would not pass the test.

?? As of version 0.31.0 (2020-11-23) the behavior of array().required() changed! Now to make sure you have at least 1 item in the array you need to sure: array().required().min(1)

Solution 3:[3]

for handle empty array error you don't need use required() and if you are using formik for handle with custom message use array().min(1, ' your message')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ciarán Tobin
Solution 2 Rodrigo Graça
Solution 3 MaK