Reputation: 109
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?
Upvotes: 17
Views: 36664
Reputation: 2911
What 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
Upvotes: 15