1
votes

I have the following as a form field type for Formik:

interface FormFields {
  groups: string[];
}

I'm trying to pass a Yup schema that will validate the above: the fact that it can be an empty array (must be defined) but can also contain strings.

The following is not working:

const schema = Yup.object({
  groups: Yup.array().defined()
}).defined();

Where am I going wrong?

2

2 Answers

5
votes

I found out that empty arrays are truthy. And after finally finding the yup docs here. I used the .min(num, message) method of Yup.array()

const validationSchema = Yup.object().shape({
  stringArray: Yup.array().min(1, messageHere);
});

you can also check if the values of your array contains strings using the array().of()

const validationSchema = Yup.object().shape({
  stringArray: Yup.array().of(Yup.string());
});
1
votes

Here is my working example. tested

let yup = require('yup')

const tSchema = yup.object().shape({
  groups: yup.array().notRequired(),
})

const u = tSchema.cast({
  groups: [],
  
})

console.log(u)