I have an array like this
{
array: ["1", "4"]
}
but I want to add a yup validation to it -- if the array is empty - so at least one item is in the array
I've tried something like this - but its not working
myArray: yup.array().min(1). required("at least one item needs to be here")
are empty arrays always truthy? Yup: Validating Array of Strings That Can Be Empty
but this sandbox seems to work? =/src/index.js
here is the formik formframe work - with checkboxes -- shown - but when the checkboxes are not selected aka value is an empty array -- the error should show - but it doesnt?
I have an array like this
{
array: ["1", "4"]
}
but I want to add a yup validation to it -- if the array is empty - so at least one item is in the array
I've tried something like this - but its not working
myArray: yup.array().min(1). required("at least one item needs to be here")
are empty arrays always truthy? Yup: Validating Array of Strings That Can Be Empty
but this sandbox seems to work? https://codesandbox.io/s/serene-khorana-3pjmq?file=/src/index.js
https://codesandbox.io/s/lively-rgb-b2sct
here is the formik formframe work - with checkboxes -- shown - but when the checkboxes are not selected aka value is an empty array -- the error should show - but it doesnt?
Share Improve this question edited May 28, 2021 at 11:53 The Old County asked May 27, 2021 at 23:23 The Old CountyThe Old County 8914 gold badges67 silver badges141 bronze badges1 Answer
Reset to default 15What you did is already correct and expected. I'm not sure what's your confusion.
If the code is:
import "./styles.css";
//import { object, array } from "yup";
import * as yup from "yup";
const mySchema = yup.object({
myArray: yup.array().min(1, "at least 1").required("required")
});
console.log("[]", mySchema.isValidSync({ myArray: [] }));
console.log(
'["John"]',
mySchema.isValidSync({
myArray: ["John"]
})
);
console.log(
'["John", "Doe"]',
mySchema.isValidSync({
myArray: ["John", "Doe"]
})
);
It returns:
[] false
["John"] true
["John", "Doe"] true
If I changed the line to
myArray: yup.array().min(2, "at least 2").required("required")
Then it returns:
[] false
["John"] false
["John", "Doe"] true