Can't validate array length
See original GitHub issueHi, kinda new to Yup and I can’t figure out how to 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
Issue Analytics
- State:
- Created 3 years ago
- Comments:6
Top GitHub Comments
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)
I am also facinga similar challenge - same set up Formik /React/ Yup- checked solutions on the documentation and stack overflow - this is what is recommended but it does not seem to work.
Validation is occurring even with a null submission – log musicGenre[0]