Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

293
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda