Yup: Validating Array of Strings That Can Be Empty
Asked Answered
S

3

19

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?

Shaunda answered 6/12, 2020 at 14:58 Comment(0)
A
48

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());
});
Automat answered 6/1, 2021 at 10:11 Comment(1)
But ``` const schema = Yup.object().shape({ phoneNumber:Yup.array().of(Yup.string()) }) schema.isValid({ phoneNumber:[1] }).then(valid=>{ console.log(valid); //gives true }) ```Wagon
C
3

This work for me:

groups: yup
    .array(
      yup.string().required(),
    )
    .min(1)

But you can use this format too:

groups: yup
        .array().of(yup.string())
        .min(1)
Conradconrade answered 27/9, 2022 at 13:23 Comment(0)
R
1

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)
Ridglea answered 9/12, 2020 at 16:19 Comment(1)
Thank you, but the array is actually required. It must be defined, and when there are indeed values inside it, they must be strings.Shaunda

© 2022 - 2024 — McMap. All rights reserved.