Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup: Validating Array of Strings That Can Be Empty

Tags:

yup

formik

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?

like image 482
Sammy Avatar asked Dec 06 '22 08:12

Sammy


1 Answers

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());
});
like image 142
Kate Banez Avatar answered Jan 14 '23 15:01

Kate Banez