0
votes

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

1

1 Answers

3
votes

You can use .min():

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