Home > Mobile >  Filter out not valid array elements based on Yup schema
Filter out not valid array elements based on Yup schema

Time:08-27

I'm using yup to validate and type data coming from API. I have the following validators and type:

export const someSchema = object({
  id: number().required(),
  name: string().required(),
  someArray: array().of(string()),
  date: dateSchema,
}).from('date', 'startDate')

export const someListSchema = array().of(someSchema)

export type SomeType = InferType<typeof someSchema>;

And it works like a charm, arrays are validated perfectly, and types are assumed as expected.

Only problem is how I validate an array, doing it in the following way:

await someListSchema.validate(data)

And if any element of an array does not meet validator requirements it throws an error and the whole validation process fails. I would like to get rid of invalid array elements and return the rest of the array. How to proceed validation with filtering out invalid elements and keeping valid?

I was trying with option { abortEarly: false }, also tried the approach with iterating through array on doing validations per element, but without success. Any ideas on how to achieve an expected result?

Regards, Bartosz.

CodePudding user response:

You could loop over the array and validate the objects individually. That way you can define your own logic on what you want to happen when object doesn't pass the validation.

For example,

export const someSchema = object({
  id: number().required(),
  name: string().required(),
  someArray: array().of(string()),
  date: dateSchema,
}).from('date', 'startDate');

const results = await Promise.allSettled(data.map((object) => someSchema.validate(object)));
const filteredResults = results.filter(({status}) => status === "fulfilled").map(({value}) => value); 
  • Related