Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
Filter out not valid array elements based on Yup schema

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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); 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!